rd42 rd42 - 4 months ago 9
MySQL Question

How to check for NULL in MySqlDataReader by the column's name?

How can I check for a

NULL
value in an open
MySqlDataReader
?

The following doesn't work; it's always hitting the
else
:

if (rdr.GetString("timeOut") == null)
{
queryResult.Egresstime = "Logged in";
}
else
{
queryResult.Egresstime = rdr.GetString("timeOut");
}


rdr.IsDbNull(int i)
only accepts a column number, not name.

Answer
var ordinal = rdr.GetOrdinal("timeOut");
if(rdr.IsDBNull(ordinal)) {
  queryResult.Egresstime = "Logged in";
} else {
  queryResult.Egresstime = rdr.GetString(ordinal);
}//if

or

if(Convert.IsDBNull(rdr["timeOut"])) {
  queryResult.Egresstime = "Logged in";
} else {
  queryResult.Egresstime = rdr.GetString("timeOut");
}//if