Mogli
Mogli

Reputation: 2012

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.

Upvotes: 3

Views: 34305

Answers (6)

izik f
izik f

Reputation: 2467

work for me:

   DataTable newDt = dt.AsEnumerable().Where(r => r["column name"] == DBNull.Value).CopyToDataTable();

if equal to null is not work because is return DBNull

Upvotes: 0

Rased Dot Net
Rased Dot Net

Reputation: 530

var rows = ds.Tables[0].AsEnumerable()
    .Where(r => r.IsNull("ParentId"));

Upvotes: 3

sll
sll

Reputation: 62484

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

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

Upvotes: 5

Moondustt
Moondustt

Reputation: 884

You can access the items like this:

 String value = ds.Tables[0].Rows[RowNum][ColNum].ToString();

Upvotes: -1

andy
andy

Reputation: 6079

Check

ds.Tables.Count

then

ds.Tables[0].Rows.Count

Upvotes: -1

Tim Schmelter
Tim Schmelter

Reputation: 460058

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)
{
    // ...
}

Upvotes: 13

Related Questions