Using OdbcDataReader in C#, I have a query that returns an integer column which could contain nulls.
For each row, I want to test whether the value is null and handle it appropriately. However, when I do this using IsDBNull I get an InvalidCastException even for rows that are not null. Why does this occur?
If I leave out the IsDBNull check, I get an error only for rows that contain nulls.
OdbcConnection DbConnection = new OdbcConnection("DSN=...");
DbConnection.Open();
OdbcCommand DbCommand = DbConnection.CreateCommand();
DbCommand.CommandText = @"
select 1 as result from dual
union
select null as result from dual";
OdbcDataReader DbReader = DbCommand.ExecuteReader();
Int32 result;
while (DbReader.Read())
{
if (!DbReader.IsDBNull(0))
{
result = DbReader.GetInt32(0); // Results in InvalidCastException
}
else
{
result = 0;
}
Console.WriteLine(Convert.ToString(result));
}
Console.ReadLine();
Edit:
The following technique to check for nulls seems to work. I would like to know why the above does not though.
object resultObject = DbReader.GetValue(0);
if (resultObject != DBNull.Value)
{
result = Convert.ToInt32(resultObject);
}
else
{
result = 0;
}
It's most likely happening because the value is not of Int32 type.
You can work out the field type with DbReader.GetFieldType(0);
Or you can handle it by converting it to an Int32 with Convert.ToInt32(DbReader.GetValue(0));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With