Check if row exists in DataTable?
you can use Contains
as below
if(DataTable.Columns.Contains("RowName"))
{
//Do some stuffs here
}
if you want to check all the cells
in a DataRow
, you can try this function:
bool ContainDataRowInDataTable(DataTable T,DataRow R)
{
foreach (DataRow item in T.Rows)
{
if (Enumerable.SequenceEqual(item.ItemArray, R.ItemArray))
return true;
}
return false;
}
You can use LINQ to check if row is present in datatable. Follow this solution, and replace "id" with your row's primary key, by which you can uniquely identify a row in a table.
DataRow dr = null; // assign your DR here
DataTable dt = new DataTable(); // assign Datatable instance here.
var k = (from r in dt.Rows.OfType<DataRow>() where r["id"].ToString() == dr["id"].ToString() select r).FirstOrDefault();
if(k != null)
{ // Row is present }
If you use a typed DataSet
, I.e. declared in design time, the "linq Contains method" takes a typed DataRow
. The default IEqualityComparer
will compare all values in the DataRow
. (Which is normally useless, since you should have a key defined).
DataSet1 ds = new DataSet1();
DataSet1.DataTable1Row row = ds.DataTable1.AddDataTable1Row(bla, bla);
bool exists = ds.DataTable1.Contains(row);