tags:

views:

356

answers:

5

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.

+6  A: 

Try:

If (data == System.DBNull)

Jon
Except that wouldn't compile. You mean either { data == System.DBNull.Value } or { data is System.DBNull }.
configurator
Yeah, i have to admit, i wrote that fast and didn't think about it.
Jon
A: 

if your data variable is a strongly typed datarow, this might help :

if(data.IsNull("ColumnName")) { ... }
Canavar
data is a SubSonic ActiveRecord
Sam
A: 

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)

Chad Grant
+1  A: 

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)
{
    ...
}
Sam
A: 

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 ...
WACM161