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:
- Make the field
NOT NULL
in the DB to ensure it cannot returnNULL
. Use a
DateTime?
instead ofDateTime
:DateTime? renewalDate = row.Field<DateTime?>("RenewalDate");
Author by
krishna mohan
Updated on June 25, 2022Comments
-
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 over 8 yearsError 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 over 8 years@krishnamohan - you can use
renewalDate.Value.Date
, but first checkrenewalDate.HasValue
to see if you really have a value. -
krishna mohan over 8 yearsi cannot use var . im using 3.5 framework@user5114524
-
krishna mohan over 8 yearsDateTime? renewalDate = row.Field<DateTime?>("RenewalDate"); if (renewalDate > DateTime.Today) e.Row.Cells[7].BackColor = System.Drawing.ColorTranslator.FromHtml("#669B1F"); else is it correct?
-
user5114524 over 8 yearsyou need to consider null value in your if stmt
-
user5114524 over 8 yearschange if :
if (renewalDate.HasValue && renewalDate.Value.Date > DateTime.Today)