8

I am accessing an MS Access 2007 database through C#, and I keep getting an exception whenever I try to read an empty cell.

Specifically, I am trying to read a "Date/Time" cell that may or may not be empty. I am using OLE DB, and have filled a DataSet. None of these conditions work:

DataSet dataSet = GetDataSet();
DataRow row = dataSet.Tables[0].Rows[0];
DateTime time = new DateTime();
time = (DateTime)row[5];   // Exception thrown

How to check if the cell is empty before trying to assign it? None of these work:

if(row[5] == null) ;
if(row[5] == DBNull) ;
if(row[5] == (String)"") ;

Edit: I should have mentioned: When I debug, it says that row[5] equals "System.DBNull,", but I get an error when I try "if(row[5] == DBNULL)". The error says "DBNULL is a type, which is not valid in the given context".

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Eric
  • 2,098
  • 4
  • 30
  • 44
  • 2
    "cell" is what you reference in a spreadsheet; it's a specific column in a record when dealing with a database. – OMG Ponies Dec 10 '10 at 05:41

3 Answers3

11

You can check it like the following.

if (row[5] == DBNull.Value)
{
    // value is null
}
else if (String.IsNullOfEmpty(Convert.ToString(row[5]))
{
    // value is still null
}
else
{
    // value is not null here
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Zain Shaikh
  • 6,013
  • 6
  • 41
  • 66
3
if(row[5] == DBNull.Value)
TalentTuner
  • 17,262
  • 5
  • 38
  • 63
0
if(Convert.IsDBNull(row[5]))
{
...
}
Liam
  • 27,717
  • 28
  • 128
  • 190
Ilaria
  • 167
  • 2
  • 13