pancake
pancake

Reputation: 600

Object DBNull Error

I tried to follow some examples on the internet without success

I'm trying the following in a GridView1_RowDataBound methode

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DataRowView drv = e.Row.DataItem as DataRowView;
        if (Convert.ToDateTime(drv["Created_Date"]).ToString("dd-MM-yyyy") == "01-01-1900" || (drv["Created_Date"].ToString().Equals(DBNull.Value))) //Check for this date
        {
            e.Row.Cells[11].Text = "test";
        }
    }
}

I'm still receiving a Object cannot be cast from DBNull to other types.

Upvotes: 0

Views: 26

Answers (1)

VDWWD
VDWWD

Reputation: 35524

You have to use

string.IsNullOrEmpty(drv["Created_Date"].ToString())

However you should switch the first and second values in the if-statement. You are checking if the Created_Date is null AFTER you cast it. So if it is null, your code will still throw an error. So it is better to do something like this

if (string.IsNullOrEmpty(drv["Created_Date"].ToString()) || Convert.ToDateTime(drv["Created_Date"]) == new DateTime(1900, 1, 1))

Upvotes: 1

Related Questions