demoshop

demo, trying to be the best_

有很多時候一些欄位不想給使用者看到,但是卻必須利用那些欄位的值作一些判斷,試過了Row.Cells和FindControl都找不到它該怎麼辦勒...以下介紹兩種方式來讓您找到隱藏的欄位值。

第一種方式算是比較小技巧的我們再GridView的RowCreated事件中撰寫以下code

  1. protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e) 
  2.     { 
  3. if (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Header) 
  4.             e.Row.Cells[0].Visible = false

 

然後在RowDataBound事件中,一樣可以利用Row.Cells的方式找到它

  1. protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
  2.     { 
  3.         if (e.Row.RowType == DataControlRowType.DataRow) 
  4.         { 
  5.             string aa = e.Row.Cells[0].Text; 
  6.         } 
  7.     } 

原因很簡單因為RowCreated事件晚於DataBinding所以它在bind以後才被隱藏當然你在RowDataBound就可以找到資料了

第二種方式看起來就比較有點水準@@
我們是直接使用ui介面把某個欄位隱藏起來(Visible = False),然後直接指定DataItem的方式去找到它,我們需要在RowDataBound事件撰寫以下code

  1. protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
  2.     { 
  3.         if (e.Row.RowType == DataControlRowType.DataRow) 
  4.         { 
  5.             Boolean draft = Convert.ToBoolean(DataBinder.Eval(e.Row.DataItem, "draft")); 
  6.             if (draft == true
  7.                 e.Row.ForeColor = System.Drawing.Color.Green; 
  8.         } 
  9.     } 

以上的code我是把draftx欄位轉換成布林,然後去判斷是真是假再去對該ROW的字色作變換

回應討論