Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot cast DBNull.Value to type 'System.DateTime', Please use nullable types

getting error while date is null . error line- DateTime renewalDate = row.Field("RenewalDate");

protected void GrdV_Projects_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow )
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
        DataRow row = ((DataRowView)e.Row.DataItem).Row;
        DateTime renewalDate = row.Field<DateTime>("RenewalDate");
        if (renewalDate.Date > DateTime.Today)
            e.Row.Cells[7].BackColor = System.Drawing.ColorTranslator.FromHtml("#669B1F");
        else
            e.Row.Cells[7].BackColor = System.Drawing.ColorTranslator.FromHtml("#FF8234");
        }
    }
}
like image 750
krishna mohan Avatar asked Sep 29 '15 06:09

krishna mohan


2 Answers

you cant convert null to date, make date-time nullable

 DateTime? renewalDate = row.Field<DateTime?>("RenewalDate")

also in your if statement

 if (renewalDate.HasValue && renewalDate.Value.Date > DateTime.Today)
like image 69
user5114524 Avatar answered Oct 03 '22 15:10

user5114524


The error is pretty clear I think. You can't assign a NULL value to a DateTime. You have two options:

  1. Make the field NOT NULL in the DB to ensure it cannot return NULL.
  2. Use a DateTime? instead of DateTime:

    DateTime? renewalDate = row.Field<DateTime?>("RenewalDate");

like image 33
Eren Ersönmez Avatar answered Oct 03 '22 14:10

Eren Ersönmez