通过字符串而不是索引获取Gridview单元格的列引用
我正在向gridview动态添加一列。。。这是一列复选框-用户通过选中它们来确定要打印的行。我希望能够在不使用数字索引的情况下获得单元格的引用:通过字符串而不是索引获取Gridview单元格的列引用,gridview,Gridview,我正在向gridview动态添加一列。。。这是一列复选框-用户通过选中它们来确定要打印的行。我希望能够在不使用数字索引的情况下获得单元格的引用: if (e.Row.RowType == DataControlRowType.DataRow) { if (e.Row.Cells[4].Controls.Count == 0) { CheckBox cbPrint = new Check
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
}
}
if(e.Row.RowType==DataControlRowType.DataRow)
{
if(e.Row.Cells[4].Controls.Count==0)
{
复选框cbPrint=新复选框();
cbPrint.ID=“chkPrint”;
cbPrint.Checked=false;
e、 Row.Cells[4].Controls.Add(cbPrint);这就是我的想法……我编写了一个小函数,根据标题文本获取列的索引
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;
}
publicstaticintgetindex(GridView-gv,string-columnText)
{
对于(int i=0;i
如果有标题文本的列,那么它将返回索引。如果没有,那么它将返回-1,您将得到一个错误…因此,如果您不知道该列是否将在那里,则需要在此处进行一些错误处理