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

9

在日期为空时出现错误。错误行为: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");
        }
    }
}

2
读取错误信息。错误信息会告诉你该做什么。 - user743382
3
使用可空的日期时间类型 DateTime? renewalDate = row.Field<DateTime?>("RenewalDate"); - harishr
4个回答

12

您无法将 null 转换为日期,将日期时间设为可为空。

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

还有在你的if语句中

 if (renewalDate.HasValue && renewalDate.Value.Date > DateTime.Today)

我不能使用var,我正在使用3.5框架。@user5114524 - krishna mohan
DateTime? renewalDate = row.Field<DateTime?>("RenewalDate"); if (renewalDate > DateTime.Today) e.Row.Cells[7].BackColor = System.Drawing.ColorTranslator.FromHtml("#669B1F"); else是的,它是正确的。 - krishna mohan
你需要在if语句中考虑空值。 - user5114524
更改为:if (renewalDate.HasValue && renewalDate.Value.Date > DateTime.Today) - user5114524

5
错误很明显,您不能将NULL值赋给DateTime。您有两个选择:
  1. 在数据库中将字段设置为NOT NULL,以确保它不会返回NULL。
  2. 使用DateTime?而不是DateTime:

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


0
请使用此代码作为您的日期时间声明:
 DateTime? renewalDate = row.Field<DateTime?>("RenewalDate");

错误25:'System.Nullable<System.DateTime>'不包含'Date'的定义,也没有接受类型为'System.Nullable<System.DateTime>'的第一个参数的扩展方法'Date'可以找到(您是否缺少使用指令或程序集引用@sanu)。 - krishna mohan
@krishnamohan - 你可以使用 renewalDate.Value.Date,但首先要检查 renewalDate.HasValue 确认你是否真的一个值。 - Hans Kesting

-1

我写了这个代码,如果有错误,请指出来。用于空值异常检查。

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

                }



        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接