简体   繁体   中英

RowDataBound : Getting value from dataTable ! Unable to cast object of type 'System.DBNull' to type 'System.String'

I'm trying in RowDataBound event to get a value from dataTable for the current editing row: Here's my code:

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

ERROR : Unable to cast object of type 'System.DBNull' to type 'System.String'. at the first line ( the one with String KK...)

How can I fix that?

Use DataItem of the GridViewRow instead of DataBinder.Eval to get the underlying datasource:

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 */}
    }
}

The Field extension method also supports nullable types.

检查DBNull.Value并检索您的数据,如果不是DBNull.Value

DBNull indicates that the value is a null value in the DB, which indicates the absence of a value. You might want to check that the query is returning valid data. If it is, you need to find a value to use when the item in the list is null.

Try this:

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

在尝试检索空值之前,需要使用“IsNull”方法来正确检查空值。

You should grab the DataRow and work off of that:

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

EDIT Another option is to use a nullable type when there's a chance that a value is null or DBNull :

var value = row.Field<decimal?>("SomeDecimalValue");
if (value.HasValue)
{

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM