2

I am Working in asp.net and c#.

I have a datatable in my application with one column.I want to iterate through that column values and check those values with someother value.please tell me how to do that.I tried it with foreach but its not working.

Code:

  foreach (DataRow dr in dt.Rows)
        {
            int code = Convert.ToInt32(dt.Rows[0]["Code"]);

            if (code == pcode)
            {
                //do something
            }
            else 
            { }
        }

Note:

dt is my datatable with column code.I want to compare all values in column code with pcode.

coder
  • 1,980
  • 3
  • 21
  • 32

4 Answers4

2
int code = Convert.ToInt32(dr["Code"]);

Although you might want to check for NULL also :)

Paul Alan Taylor
  • 10,474
  • 1
  • 26
  • 42
1

Inside your loop, access dr, instead of dt.Rows[0].

Oskar Berggren
  • 5,583
  • 1
  • 19
  • 36
0

You are always accessing the first row:

dt.Rows[0]["Code"]  // use dr instead of dt.Rows[0]

dt is my datatable with column code.I want to compare all values in column code with pcode.

So am i right when i assume that you want to compare all values with one variable, if all fields equal this value, a bool variable should be true, otherwise false?

You can use Linq:

var allEqual = dt.AsEnumerable()
                 .All(r => r.Field<int>("Code") == pcode);

Enumerable.All determines whether all elements of a sequence satisfy a condition.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0
foreach (DataRow dr in dt.Rows)
{
    object o = dr["Code"];
    if (o != DBNull.Value) // Check for null
    {
        int code = Convert.ToInt32(o);

        if (code == pcode)
        {
            //do something
        }
        else 
        { }
    }
}
Mohammad Dehghan
  • 17,853
  • 3
  • 55
  • 72