views:

234

answers:

5

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.

+8  A: 

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
   }
jball
This looks like the correct way. As it says in the above link "The following example calls the DBNull.Value.Equals method to determine whether a database field in a contacts database has a valid value. If it does, the field value is appended to the string output in a label."
soldieraman
A: 

row.IsNull("column")

jspcal
A: 

Just check for

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

or you could

if(t.Rows[0].IsNull(0))
{
     //Whatever I want to do
}
Rabbi
table.rows[0][0] == null fails thats why I was using the .ToString() and then checking using String.IsNullOrEmpty
soldieraman
the IsNull method would work, but you can't compare null to null directly; null == null is false. At best, you8 have to compare to DBNull.Value
Val
A: 

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

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

Marcin Seredynski
+2  A: 

The prefered method would be to use DataRow.IsNull. It has some overrides which accept the column as an index, a name, or the DataColumn object.

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 what you need (comparing with null won't work, that is why String.IsNullOrEmpty doesn't work)

And if you want something which isn't a DataRow to compare with DbNull you can always use Convert.IsDBNull.

Protron