Error Object cannot be cast from DBNull to other types.

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.

About these ads


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.