2008年5月20日 星期二

在GridView RowDataBound 如何取得不存在GridView 內的欄位資料

實務上我們不會每次都將 DataSource 所有的欄位顯示在 GridView 裡面,但當我們需要的欄位不在GridView 上時,要如何去取得這個欄位的值呢?
答案就是在GridView RowDataBound 這個 event 傳進來的 GridViewRowEventArgs e 這個 Object:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{

if (e.Row.RowType == DataControlRowType.DataRow)

{



//object refundAmt = DataBinder.Eval(e.Row.DataItem, "RefundAmt");

int refundAmt = ((usp_select_NetATM_logby_TransNoResult1)e.Row.DataItem).RefundAmt;



if (refundAmt > 0)

{

object OrderInfo = e.Row.FindControl("OrderInfo");

if (OrderInfo != null)

{

((Label)OrderInfo).Text += "
";

}

object RefundDetailLink = e.Row.FindControl("RefundDetailLink");

if (RefundDetailLink != null)

{



((HyperLink)RefundDetailLink).NavigateUrl = "javascript:MM_openBrWindow('RefundDetail.aspx?TransNo=" + e.Row.Cells[2].Text.TrimEnd() + "','NewWindow','width=850,height=600,toolbar=no, menubar=no,location=no')";

((HyperLink)RefundDetailLink).Text = "(已執行退費與沖正)";

}
}


e.Row.DataItem 會存放原始DataSource 作 row databound 的資料,所以可以從這裡取的你要的欄位值,要注意的是這個DateItem 的Type 是根據你原來的DataSource而定的,所以你需要事先知道,然後轉型才可以用,偷懶一點的寫法是用DataBinder.Eval 這個Method,由.Net幫你作轉型, 只是這個方法會用到reflection 的機制,遇到大量的資料時,可能會有效能上的問題。

請參考
http://weblogs.asp.net/rajbk/archive/2004/07/20/what-s-the-deal-with-databinder-eval-and-container-dataitem.aspx