Test for DBNULL?

  • Thread starter Thread starter Arne
  • Start date Start date
A

Arne

The code below complies but it does not test to DBNull.
What am I doing wrong?

DataRow row = Data.Tables[0].Rows[0];
Type t = row[1].GetType();
if ( row[1].GetType() != typeof( DBNull) )
{
i= Convert.ToInt32(row[1]);
}
 
Out of my head: this code will throw an exception when row[1] == null.
I'd do it like:

if (row[1] != DBNull.Value)
{

}

or even better,
if (!row.IsNull(1))
{
}
 
Miha has hit it on the head, as usual.

Also, with strongly typed DataSets, if you ever decide to go this route, you
will get an Is{fieldName}Null() method for each nullable field. I am not
suggesting putting in STDs, but it is a very easy to use option.

--
Gregory A. Beamer
MVP: MCP: +I, SE, SD, DBA

Blog:
http://feeds.feedburner.com/GregoryBeamer

********************************************
| Think Outside the Box! |
********************************************
 
Back
Top