对象 DBNull 错误

Object DBNull Error

我尝试按照互联网上的一些示例进行操作,但没有成功

我正在 GridView1_RowDataBound 方法中尝试以下操作

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DataRowView drv = e.Row.DataItem as DataRowView;
        if (Convert.ToDateTime(drv["Created_Date"]).ToString("dd-MM-yyyy") == "01-01-1900" || (drv["Created_Date"].ToString().Equals(DBNull.Value))) //Check for this date
        {
            e.Row.Cells[11].Text = "test";
        }
    }
}

我仍然收到 对象无法从 DBNull 转换为其他类型。

你必须使用

string.IsNullOrEmpty(drv["Created_Date"].ToString())

但是您应该在 if-statement 中调换第一个和第二个值。您正在检查 Created_Date 是否为 null 施法后。所以如果它是 null,你的代码仍然会抛出错误。所以最好做这样的事情

if (string.IsNullOrEmpty(drv["Created_Date"].ToString()) || Convert.ToDateTime(drv["Created_Date"]) == new DateTime(1900, 1, 1))