C# DataTable ItemArray returns '{}' - how can I test for null value?

Nick Josevski picture Nick Josevski · Apr 2, 2009 · Viewed 25.2k times · Source

I have a DataTable resultSet; - I'm trying to check fields for null, but get an '{}' (empty-set ?) object back. Searches involving "{}" aren't yielding any appropriate solutions.

This is the code that isn't working as expected when the "fk_id" field is null:

if (resultSet.Rows[0].ItemArray[resultSet.Columns.IndexOf("fk_id")] == null)
{
   //never reaches here
}

Note: using an int index instead of the Columns.IndexOf() isn't the issue.

Also does the "{}" have some other name in C#?

Answer

Matt Hamilton picture Matt Hamilton · Apr 2, 2009

To check a column for DBNull in a DataSet, you can use the IsNull method:

if (resultSet.Rows[0].IsNull("fk_id"))

Your comparison against null is probably failing because DataSets don't use null to represent a "database NULL" value - they use DBNull.Value. If you need your code to work the way you've presented it, try this:

if (resultSet.Rows[0].ItemArray[resultSet.Columns.IndexOf("fk_id")] == DBNull.Value)