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)
我认为这个错误非常明显。您不能将 NULL 值分配给DateTime. 您有两个选择:
NOT NULL在DB中确保不能返回NULL。使用 aDateTime?代替DateTime:
DateTime? renewalDate = row.Field<DateTime?>("RenewalDate");
您不能将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)
| 归档时间: |
|
| 查看次数: |
8492 次 |
| 最近记录: |