When my website gets to the following bit of code, it falls down with an exception as follows:
System.InvalidCastException: Object cannot be cast from DBNull to other types.
For the interests of brevity, I'm showing only the relevant code (it's a 4000+ LOC file I've been given).
if (dr["STAGE"] is DBNull)
{
dto.Stage = 1; // This is the line throwing the exception, according to stack trace
}
else
{
dto.Stage = Convert.ToInt32(dr["STAGE"]);
}
Here, dr
is a DataRow object that is the result of a query to a database, dto
is a basic class that just holds some properties, of which dto.Stage
is an int
member.
I've looked at other questions with the same error message, but most of them seem to suggest "Check if it's DBNull", which I'm already doing.
So can someone suggest a solution?
Use ==
instead of is
if (dr["STAGE"] == DBNull.Value)
{
}
Use this slightly more efficient approach
int stageOrdinal = dr.GetOrdinal("STAGE");
while (dr.Read()) {
dto = new DataTransferObject();
if (dr.IsDBNull(stageOrdinal)) {
dto.Stage = 1;
} else {
dto.Stage = dr.GetInt32(stageOrdinal);
}
//TODO: retrieve other columns.
dtoList.Add(dto);
}
Accessing the columns by their index is faster than accessing them by name. The index of a column can be retrieved with the GetOrdinal
method of the DataReader
. This is best done before the loop.
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