2012-04-24 101 views

回答

12

使用DataItem獲得底層數據源:

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 extension method也支持可空類型。

0

在嘗試檢索它之前,您需要使用「IsNull」 - 方法來正確檢查空值。在GridViewRow代替DataBinder.Eval

+0

好的是,列單元格值永遠不會爲空,因爲用戶無法編輯它們/ – 2012-04-24 13:40:44

1

檢查DBNull.Value和檢索數據如果不是DBNull.Value

1

的DBNull表示該值是 數據庫,這表明沒有值的空值。您可能需要檢查 該查詢是否返回有效數據。如果是這樣,當列表中的項爲空時,您需要找到值 。

試試這個:

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

你應該抓住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) 
{ 

} 
相關問題