Looping through data table to get value

喜你入骨 提交于 2020-12-26 05:14:37

问题


I have a DataTable with multiple rows. I'm using a foreach loop to loop through each item and return the name. This is returning the same (1st) value for each row. What have I done wrong?

            DataTable table = new DataTable();
            table.Columns.Add("tag", typeof(string));
            string name = hfSelected.Value;
            string[] names = name.Split(',');
            for (int i = 0; i < names.Length; i++)
                table.Rows.Add(new object[] { names[i] });                  
            DataRow row = table.Rows[0];

            foreach (var item in table.Rows)
            {

                Value = row["tag"].ToString() // this is returning the same value for both items in the table.

            }

回答1:


In a comment you mentioned that you get the error:

cannot apply indexing with [] to an expression of type object

when trying to access item["tag"] in the foreach loop.

You need to explicitly declare the DataRow in the foreach.

// declare DataRow here, not var 
foreach (DataRow item in table.Rows)
{
    // use item here
    Value = item["tag"].ToString();    // use += to concatenate string
}

The reason is that the DataRowCollection implements a non-generic IEnumerable so you index an object instead of DataRow. The solution above casts to a DataRow.

I would recommend looking at the Field<T>() and AsEnumerable() methods from System.Data.DataSetExtensions. AsEnumerable() returns an IEnumerable<DataRow>. Field() provides strongly typed access to the values (ie it casts/converts the types for you).

Then you can do:

foreach (var item in table.AsEnumerable())
{
    // item is a DataRow here
    var myString = item.Field<string>("tag");     // gets string

    // you can also do
    var myInt = item.Field<int>("Id");            // gets int
    var myDate = item.Field<DateTime?>("Date");   // gets nullable DateTime?
    var myValue = item.Field<decimal>("Price");   // gets decimal
}



回答2:


Carl is correct, this is producing the same output, because inside the iteration, you use the same row, all the time. You should use 'item', instead of 'row' there (you don't need 'row' at all).

The exception you receive is because you declared 'item' with a dynamic type, it's

 foreach (var item in table.Rows)

You can try

 foreach (DataRow item in table.Rows)

this way, you'll be able to get the column info.




回答3:


your iteration seems to be using the same 'row' variable instead of the 'item' variable you defined in the foreach statement.



来源:https://stackoverflow.com/questions/55306299/looping-through-data-table-to-get-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!