Object cannot be cast from DBNull to other types

Sometimes you need to code around dates in your program. Today i will discuss about the common error we get while displaying a date from back end to front end. What if you have blank/null value inserted in your back end for date and when you get this date to front end and try to bind this in a text box control then you will get a common error …

“Object cannot be cast from DBNull to other types”

No problem you have to put a check before binding the date in text box like below:

if (drPublication[strReleaseDate] != System.DBNull.Value )
{
this.dtTest.SelectedDate = Convert.ToDateTime(drPublication[strReleaseDate]);
}