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

13,850

Solution 1

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)

Solution 2

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");

Share:
13,850
krishna mohan
Author by

krishna mohan

Updated on June 25, 2022

Comments

  • krishna mohan
    krishna mohan almost 2 years

    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");
            }
        }
    }
    
  • krishna mohan
    krishna mohan over 8 years
    Error 25 'System.Nullable<System.DateTime>' does not contain a definition for 'Date' and no extension method 'Date' accepting a first argument of type 'System.Nullable<System.DateTime>' could be found (are you missing a using directive or an assembly referenence@sanu
  • Hans Kesting
    Hans Kesting over 8 years
    @krishnamohan - you can use renewalDate.Value.Date, but first check renewalDate.HasValue to see if you really have a value.
  • krishna mohan
    krishna mohan over 8 years
    i cannot use var . im using 3.5 framework@user5114524
  • krishna mohan
    krishna mohan over 8 years
    DateTime? renewalDate = row.Field<DateTime?>("RenewalDate"); if (renewalDate > DateTime.Today) e.Row.Cells[7].BackColor = System.Drawing.ColorTranslator.FromHtml("#669B1F"); else is it correct?
  • user5114524
    user5114524 over 8 years
    you need to consider null value in your if stmt
  • user5114524
    user5114524 over 8 years
    change if : if (renewalDate.HasValue && renewalDate.Value.Date > DateTime.Today)