krishna mohan
krishna mohan

Reputation: 267

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

Upvotes: 10

Views: 19667

Answers (4)

krishna mohan
krishna mohan

Reputation: 267

i have wrote this if any wrong please suggest me . for null exception checking

 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");
                    DateTime? renewalDate = row.Field<DateTime?>("RenewalDate");
                    if (renewalDate > DateTime.Today)
                        e.Row.Cells[7].BackColor = System.Drawing.ColorTranslator.FromHtml("#669B1F");
                    else
                        e.Row.Cells[7].BackColor = System.Drawing.ColorTranslator.FromHtml("#FF8234");

                }



        }
    }

Upvotes: -1

user5114524
user5114524

Reputation: 146

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)

Upvotes: 13

Eren Ers&#246;nmez
Eren Ers&#246;nmez

Reputation: 39085

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

Upvotes: 5

Sanu Antony
Sanu Antony

Reputation: 364

Use this as your datetime deceleration

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

Upvotes: 0

Related Questions