"Object cannot be cast from DBNull to other types"

TZHX picture TZHX · Jun 26, 2012 · Viewed 13k times · Source

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?

Answer

Aelios picture Aelios · Jun 26, 2012

Use == instead of is

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

}