0

In my application i am filtering a datatable using a filter expression and am getting a DataRow which matches the condition.Now i want to check if the value of particular column exists in any row of DataRow array.

Code:

string FilterCond1 = "id=" + getId;
DataRow[] myrow = DataTable.Select(FilterCond1);
if (myrow.Length > 0)
{
//check for size=28 in DataRow[]
}
else
{
}

I have column size in the datatable DataTable and i want to check if any row of the DataRow array has a value 28 in the column size.How can i go about it?

smith269
  • 135
  • 2
  • 4
  • 15

3 Answers3

3

Try this

string FilterCond1 = "id=" + getId;
DataRow[] myrow = DataTable.Select(FilterCond1);
if (myrow.Length > 0)
{
  for(int i = 0; i < myrow.Length; i ++)
  {
    if(myrow[i]["size"].ToString() == "28")
    {
      // YOUR CODE HERE 
    }
  }
}
else
{
}

EDIT

Just add the condition to your filter.

string FilterCond1 = "id=" + getId + " AND size=28";

Then you don't need the if(myrow[i]["size"].ToString() == "28") as you know the rows in the array are the one you want.

Jack Pettinger
  • 2,715
  • 1
  • 23
  • 37
1

You can use column collection to access particular column value within row.

if(myrow[rowIndex]["ColoumnName"].ToString() == "somevalue")

Where row index could from zero to length-1

Edit based on comments, you can put multiple condition on column in select, check it here, and may not need to iterate.

string FilterCond1 = "id=" + getId + " AND size = " + 28;
DataRow[] myrow = dt.Select(FilterCond1);

To iterate through rows collection

for(int i=0; i < myrow.Length; i++)
{
   if(myrow[i]["size"].ToString() == "28")
   {
        //your code
   }
}
Community
  • 1
  • 1
Adil
  • 146,340
  • 25
  • 209
  • 204
  • Its giving me an error cannot implicitly convert type string to int. – smith269 Apr 10 '13 at 10:15
  • You would be comparing string with int, change condition to if(int.Parse(myrow["ColoumnName"].ToString()) == 123) – Adil Apr 10 '13 at 10:16
  • Sorry I thought myrow is row object but it row object array, you need to use indexer, if(myrow[0]["ColoumnName"].ToString() == "somevalue") also check my updated answer – Adil Apr 10 '13 at 10:58
  • I know we should use row indexer.But i want check in all rows whether the value exists. – smith269 Apr 10 '13 at 11:09
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/27939/discussion-between-adil-and-smith269) – Adil Apr 10 '13 at 11:18
0

First you should aiterate through all rows using foreach then use the below code..

if(myrow[row]["size"] == 28)

or

int ColIndex = 3; // replace 3 with ur co. index 
if(myrow[row][ColIndex] == 28)
Popeye
  • 11,839
  • 9
  • 58
  • 91
Jo9876
  • 13