"Object cannot be cast from DBNull to other types"
c#, datarow
Solution
@MarcGravell had the right of it in his comment:
Ignore the exact line number in the stack-trace; the numbers can be slightly off - I see that all the time. Run it in a debugger with break-points instead, or just add extra logging while you nail it down
@Sergey's answer is just plain wrong.
Problem
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?