I have a table which contains null values and I need to get data from the table using SqlDataReader. I can't figure out how I can safely cast DBNull to int.
I'm doing it in this way at the moment:
...
reader = command.ExecuteReader();
while (reader.Read()) {
int y = (reader["PublicationYear"] != null) ? Convert.ToInt32(reader["PublicationYear"]) : 0;
...
}
...
but getting a Object cannot be cast from DBNull to other types.
when PublicationYear is null.
How can I get the value safely?
Thanks.
You should compare
reader["PublicationYear"]
toDBNull.Value
, notnull
.That's the error:
(reader["PublicationYear"] != null)
You should test for DBNull.Value....Database null values should be compared with DBNull.Value
reader = command.ExecuteReader(); while (reader.Read()) { int y = (reader["PublicationYear"] != DBNull.Value) ? Convert.ToInt32(reader["PublicationYear"]) : 0; ... }