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

时间:2015-09-29 06:22:13

标签: c# asp.net datetime casting

日期为空时获取错误。错误行 - 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");
        }
    }
}

4 个答案:

答案 0 :(得分:4)

你不能将null转换为日期,使日期时间可以为空

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

也在你的if语句中

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

答案 1 :(得分:3)

我认为错误很清楚。您无法为DateTime分配NULL值。您有两种选择:

  1. 在数据库中创建字段NOT NULL,以确保无法返回NULL
  2. 使用DateTime?代替DateTime

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

答案 2 :(得分:0)

将此用作日期时间减速

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

答案 3 :(得分:-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");

                }



        }
    }