行数据绑定:从数据表中获取值!无法将类型为“System.DBNull”的对象强制转换为类型“System.String

本文关键字:类型 System DBNull 对象 String 转换 数据表 数据绑定 获取 | 更新日期: 2023-09-27 18:32:09

我正在尝试在 RowDataBound 事件中从 dataTable 中获取当前编辑行的值:这是我的代码:

string KK = (string)DataBinder.Eval(e.Row.DataItem, "Name");
if ( KK == "John" )
{
//execute code
}

错误:无法将类型为"System.DBNull"的对象转换为类型"System.String"。 在第一行(带有字符串 KK 的那个...

我该如何解决这个问题?

行数据绑定:从数据表中获取值!无法将类型为“System.DBNull”的对象强制转换为类型“System.String

使用GridViewRowDataItem而不是DataBinder.Eval来获取基础数据源:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState == DataControlRowState.Edit))
    {
        DataRow row = ((DataRowView)e.Row.DataItem).Row;
        String name = row.Field<String>("Name");
        // String is a reference type, so you just need to compare with null
        if(name != null){/* do something */}
    }
}

Field扩展方法还支持可为 null 的类型。

检查DBNull.Value,如果不是DBNull.Value,则检索数据

DBNull 指示该值是 null 值DB,指示缺少值。您可能需要检查查询返回有效数据。如果是,则需要找到一个值在列表中的项为 null 时使用。

试试这个:

string KK = DataBinder.Eval(e.Row.DataItem, "Name").GetType() == typeof(System.DBNull) ? "" : (string)DataBinder.Eval(e.Row.DataItem, "Name")

您需要使用 "IsNull" 方法正确检查空值,然后才能尝试检索它。

你应该

抓住DataRow并解决这个问题:

var row = e.Row.DataItem as DataRow;
if (row != null)
{
    //for strings this will work fine
    var name = row.Field<string>("Name");
    //for other types use the IsNull function to check for DBNull
    if (!row.IsNull("SomeDecimalValue"))
        var value = row.Field<decimal>("SomeDecimalValue");
}

编辑 另一种选择是在值可能nullDBNull时使用可为空的类型:

var value = row.Field<decimal?>("SomeDecimalValue");
if (value.HasValue)
{
}
相关文章: