3

I have DataTable with a primary key with multiple columns

dt.PrimaryKey = new DataColumn[] {dt.Columns["Name"], dt.Columns["Type"] };

Now I want to check if my DataTable dt contains (Adarsh, Developer)

I have to pass two values in Contains Method

I tried using the following which doesn't seem to work

DataRow dr = dt.Rows(e.RowIndex); 
DataRow drNew = dt.NewRow();
drNew["Name"] = dr["Name"];
drNew["Type"] = dr["Type"];
drNew["Address"] = dr["Address"];

if(dt.Rows.Contains(drNew["Name"].ToString(), drNew["Type"].ToString())) //This gives me an error
{
}

Thank You in advance

Adarsh Ravi
  • 893
  • 1
  • 16
  • 39

3 Answers3

7

The DataRowCollection.Contains overload you want to use has a single parameter: Object[] keys, but you're trying to pass two arguments.

You have to pack the keys into an Object[]:

dt.Rows.Contains(new object[]{first_value, second_value})

If you think it's ugly, you could wrap it in a simple extension method like this:

public static class Extenstions
{
    public static bool Contains(this DataRowCollection c, params object[] args)
    {
        return c.Contains(args);
    }
}

which would enable you to call it the way you do, like

dt.Rows.Contains(first_value, second_value)
sloth
  • 99,095
  • 21
  • 171
  • 219
1

You can try Select().

DataRow[] result = table.Select("Name = 'foo' and Type = 'bar'");

And then see if result count is greater then 0.

MaticDiba
  • 895
  • 1
  • 11
  • 19
0

LINQ is much easier to accomplish a very similar result

string name = "Bill";
bool hasValue = dt.AsEnumerable().Any(row => 'value' == row.Field<String>("Name"));

..also a very similar question can be found here Check if value exists in dataTable?

Heinrich
  • 36
  • 6