Best way to check if column returns a null value (from database to .net application)

133,533

Solution 1

Use DBNull.Value.Equals on the object without converting it to a string.

Here's an example:

   if (! DBNull.Value.Equals(row[fieldName])) 
   {
      //not null
   }
   else
   {
      //null
   }

Solution 2

Just use DataRow.IsNull. It has overrides accepting a column index, a column name, or a DataColumn object as parameters.

Example using the column index:

if (table.rows[0].IsNull(0))
{
    //Whatever I want to do
}

And although the function is called IsNull it really compares with DbNull (which is exactly what you need).


What if I want to check for DbNull but I don't have a DataRow? Use Convert.IsDBNull.

Solution 3

System.Convert.IsDbNull][1](table.rows[0][0]);

IIRC, the (table.rows[0][0] == null) won't work, as DbNull.Value != null;

Solution 4

row.IsNull("column")

Share:
133,533
soldieraman
Author by

soldieraman

Updated on February 21, 2020

Comments

  • soldieraman
    soldieraman about 4 years

    I have a table with a DateTime column the column can have NULL values

    Now I connect to the database using an ODBC connection and get the value into a DataTable in .net / c#.

    I am able to check it for NULL by going

    if(String.IsNullOrEmpty(table.rows[0][0].ToString())
    {
         //Whatever I want to do
    }
    

    Is String.IsNullOrEmpty the correct way to check for null values.