Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
416 views
in Technique[技术] by (71.8m points)

c# - Looping through data table to get value

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.

            }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...