无法将DBNull.Value强制转换为“ System.DateTime”类型,请使用可为空的类型

kri*_*han 4 c# asp.net datetime casting

date为null时出错。错误行-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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Ere*_*mez 5

我认为这个错误非常明显。您不能将 NULL 值分配给DateTime. 您有两个选择:

  1. 使该字段NOT NULL在DB中确保不能返回NULL
  2. 使用 aDateTime?代替DateTime

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


use*_*524 5

您不能将null转换为日期,而将date-time设置为null

 DateTime? renewalDate = row.Field<DateTime?>("RenewalDate")
Run Code Online (Sandbox Code Playgroud)

同样在你的if语句中

 if (renewalDate.HasValue && renewalDate.Value.Date > DateTime.Today)
Run Code Online (Sandbox Code Playgroud)