Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check IS NULL on DataTable?

In my case i am passing a sql query and getting data in dataset, but problem occurs when i try to get the rows where ParentId column contain NULL.This is the piece of code.

   DataSet ds = GetDataSet("Select ProductId,ProductName,ParentId from ProductTable");

   //ds is not blank and it has 2 rows in which ParentId is NULL

   DataRow[] Rows = ds.Tables[0].Select("ParentId IS NULL");

But still i am not getting any rows. Need help. Thanx.

like image 921
Mogli Avatar asked Feb 25 '26 10:02

Mogli


2 Answers

Use the strongly typed DataRow extension method Field which also supports nullable types:

IEnumerable<DataRow> rows = ds.Tables[0].AsEnumerable()
    .Where(r => !r.Field<int?>("ParentId").HasValue);

Note that i've used Enumerable.Where which is a Linq extension method to filter the table.

If you want an array use ToArray, if you want a new DataTable use CopyToDataTable. If you simply want to enumerate the result use foreach.

foreach(DataRow row in rows)
{
    // ...
}
like image 70
Tim Schmelter Avatar answered Feb 28 '26 00:02

Tim Schmelter


var rowsWithoutParent = dt.AsEnumerable().Where(r => r["ParentId"] == null);

var rowsWithParent = dt.AsEnumerable().Where(r => r["ParentId"] != null);
like image 44
sll Avatar answered Feb 28 '26 02:02

sll



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!