Sunday, May 1, 2011

How to check for null values?

I have an integer column that may have a number or nothing assigned to it (i.e. null in the database). How can I check if it is null or not?

I have tried

if(data.ColumnName == null)
{
    ...
}

This doesn't work either (as SubSonic does not use nullable types (when applicable) for ActiveRecord)

if(data.ColumnName.HasValue)
{
    ...
}

If the value stored in the database is 0, then this wouldn't help:

if(data.ColumnName == 0 /* or 0x000? */)
{
    ...
}

The same problem could also occur with DateTime fields as well.

From stackoverflow
  • Try:

    If (data == System.DBNull)

    configurator : Except that wouldn't compile. You mean either { data == System.DBNull.Value } or { data is System.DBNull }.
    Jon : Yeah, i have to admit, i wrote that fast and didn't think about it.
  • if your data variable is a strongly typed datarow, this might help :

    if(data.IsNull("ColumnName")) { ... }
    
    Sam : data is a SubSonic ActiveRecord
  • DBNull is the value of a null column.

    DBNull is a value type. Value types cannot be null.

    Assuming a SqlDataReader ... checking for null is :

    if (reader["colname") == DBNull.Value)

  • Found out how to do it. SubSonic has a method for getting the value as an object to allow a null check:

    if(data.GetColumnValue("Column Name") == null)
    {
        ...
    }
    
  • When querying the database handle the null there, makes your life a lot easier in the code

    SQL example

    SELECT isNull(columnName, 0) FROM TABLENAME...
    

    or

    Select isNUll(columnName, 'N/A') FROM TABLENAME ...
    

0 comments:

Post a Comment