Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Object cannot be cast from DBNull to other types"

Tags:

c#

datarow

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?

like image 952
TZHX Avatar asked Jun 26 '12 14:06

TZHX


2 Answers

Use == instead of is

if (dr["STAGE"] == DBNull.Value)
{

}
like image 184
Aelios Avatar answered Oct 22 '22 05:10

Aelios


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.

like image 42
Olivier Jacot-Descombes Avatar answered Oct 22 '22 04:10

Olivier Jacot-Descombes