Kamran
Kamran

Reputation: 4100

c# How to get Dataset contents in loop

I have a Dataset ds1 and I have selected a column in it from a table.

da = new SqlDataAdapter("Select column from table", con); // con is the connection string
da.Fill(ds1, "column");

Then I assigned the contents from first row to a string array getitems[] as follows:

getitems[0] = (ds1.Tables[0].Rows[0]["column"].ToString());

Every thing is working fine if I use it in this way but the data set contains 600 rows.I used the above statement in a loop but I am getting an error. Here is the code:

for(int i=0; i<=600; i++) {

getitems[i] = (ds1.Tables[i].Rows[i]["column"].ToString());
dt.Rows.Add(getitems[i]);
//dt is another data set and is putting the data on a data grid
}

I am get this exception on the line where I am assigning the contents to string array:

Exception Details: System.IndexOutOfRangeException: Cannot find table 1.

Upvotes: 1

Views: 1132

Answers (2)

Surya Narayan
Surya Narayan

Reputation: 558

Try this one

for(int i=0; i<600; i++) {
    getitems[i] = Convert.ToString(ds1.Tables[0].Rows[i]["column"]);
    //Some logic
}

Upvotes: 1

Joe Ratzer
Joe Ratzer

Reputation: 18569

Your DataSet doesn't have 600 tables!

This isn't right - Tables[i]

Use the loop for just the rows and instead of using 600 use Count on the rows or use a foreach loop. Something like:

 var dt = ds1.Tables[0];
 foreach (DataRow row in dt.Rows) 
 {
    foreach (DataColumn col in dt.Columns)

Upvotes: 3

Related Questions