2011-04-08 61 views
0

我正在動態地向GridView添加一列......它是一列複選框 - 用戶檢查它們以確定他們想要打印的行。我想能夠得到的單元格引用,而無需使用數字索引:通過字符串而不是索引獲取Gridview單元格的列引用

 if (e.Row.RowType == DataControlRowType.DataRow) 
     { 
      if (e.Row.Cells[4].Controls.Count == 0) 
      { 
       CheckBox cbPrint = new CheckBox(); 
       cbPrint.ID = "chkPrint"; 
       cbPrint.Checked = false; 
       e.Row.Cells[4].Controls.Add(cbPrint); <--- this line 
      } 
     } 

我想能夠使用「打印」在e.Row.Cells [「打印」]像您可以使用DataSet中的列 - 例如:ds.Tables [0] .Rows [3] [「Print」],其中,print指定列。我希望能夠這樣做,因爲打印列可能不在每個GridView中的相同位置,並且使用數字索引可能無法一直工作。有沒有辦法使用字符串列引用獲取單元格?

回答

0

這就是我想到的......我寫了一個小函數來根據標題文本獲取列索引。

 GridView gv = (GridView)sender //inside OnRowDataBound 
     if (e.Row.RowType == DataControlRowType.DataRow) 
     { 
      if (e.Row.Cells[GetIndex(gv, "Print")].Controls.Count == 0) 
      { 
       CheckBox cbPrint = new CheckBox(); 
       cbPrint.ID = "chkPrint"; 
       cbPrint.Checked = false; 
       e.Row.Cells[GetIndex(gv, "Print")].Controls.Add(cbPrint); 
      } 
     } 

的GetIndex方法:

 public static int GetIndex(GridView gv, string columnText) 
     { 
      for (int i = 0; i < gv.Columns.Count; i++) 
       if (gv.Columns[i].HeaderText == columnText) 
        return i; 
      return -1; 
     } 

如果具有該標題文本列是存在的,那麼它將返回的索引。如果沒有,那麼它將返回-1,你會得到一個錯誤...所以如果你不知道列是否在那裏,那麼在這裏需要一些錯誤處理。

相關問題