Error Object cannot be cast from DBNull to other types.
Posted: 22/02/2012 Filed under: Programming | Tags: C#, Error Leave a comment »This happens when the database is returning an object of type DBNull. Best approach towards handling this error would be to check if the object is of type DBNull first, before attempting to use it. Sample snippet below demonstrates this, using the Convert.IsDBNull method.
1: var reader = command.ExecuteReader() // assumes SqlCommand has been initialised
2:
3: if(!Convert.IsDBNull(reader["DateInDatabase"])) // if it is not returning DBNull
4: {
5: // Do Something
6: }
Hope this helps.