2011-04-08 102 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,你会得到一个错误...所以如果你不知道列是否在那里,那么在这里需要一些错误处理。

相关问题