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.
Change
null
toDBNull.Value
.You must call
rdr.IsDBNull(column)
to determine if the value isDbNull
.You can also do:
If (string.IsNullOrEmpty(rdr.GetString("timeOut"))
Here's one I like:
E.g. (for the original requirement):
You can compare the object that retrive from NULL field with DBNull.Value.
Here is a method that I created to read
DBNull
and return adefault(T)
incase:It can be used like this:
The generic type
T
will be resolved based on the return value of thereader.
- method. If it returns a string you will receive anull
incase ofDBNull
. If it is anint
it will return0
, etc.Note: for integer values it might not be desired to get a
0
so be careful.