How to safely cast nullable result from sqlreader to int?
Solution 1
You should compare reader["PublicationYear"]
to DBNull.Value
, not null
.
Solution 2
DBNull
is not the same as null
. You should try something like this instead:
int y = (reader["PublicationYear"] != DBNull.Value) ? ...
Solution 3
int ord = reader.GetOrdinal("PublicationYear");
int y = reader.IsDBNull(ord) ? 0 : reader.GetInt32(ord);
Or, alternatively:
object obj = reader["PublicationYear"];
int y = Convert.IsDBNull(obj) ? 0 : (int)obj;
Solution 4
as an alternative you can do the following. as you are converting DBNull to 0, alter the procedure that does the select. so that the select itself returns zero for a null value.
snippet to demonstrate the idea
SELECT ...
,ISNULL (PublicationYear, 0) as PublicationYear
...
FROM sometable
advantage of this is that, no additional checking is needed in your code.
Solution 5
Change
reader["PublicationYear"] != null
to
reader["PublicationYear"] != DBNull.Value
Burjua
Updated on June 28, 2022Comments
-
Burjua almost 2 years
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.