Shane
Shane

Reputation: 542

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.

            }

Upvotes: 0

Views: 17947

Answers (3)

haldo
haldo

Reputation: 16691

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
}

Upvotes: 5

P&#233;ter Kuti
P&#233;ter Kuti

Reputation: 21

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.

Upvotes: 0

Carl Verret
Carl Verret

Reputation: 616

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

Upvotes: -1

Related Questions