简体   繁体   English

循环获取数据集内容

[英]c# How to get Dataset contents in loop

I have a Dataset ds1 and I have selected a column in it from a table. 我有一个数据集ds1,并且从表中选择了一个列。

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 [] ,如下所示:

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. 如果我以这种方式使用它,那么一切都可以正常工作,但是数据集包含600行。我在循环中使用了以上语句,但出现错误。 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.

Your DataSet doesn't have 600 tables! 您的数据集没有600个表!

This isn't right - Tables[i] 这是不对的- Tables[i]

Use the loop for just the rows and instead of using 600 use Count on the rows or use a foreach loop. 仅对行使用循环,而不是对行使用600,而对行使用Count或使用foreach循环。 Something like: 就像是:

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

Try this one 试试这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM