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

asp.net, c#, sql

Solution

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.

Problem

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?

Original source