Getting the column reference of a Gridview Cell by string instead of index
I'm adding a column to a gridview dynamically... it is a column of checkboxes - users check them to determine which row they want to print. I would like to be able to get the reference to a cell without using the numerical index:
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
}
}
I would like to be able to use "Print" as in e.Row.Cells["Print"] like you can with columns in a DataSet - like: ds.Tables[0].Rows[3]["Print"], where print specifies the column. I would like to be able to do this because the print column may not be in the same place in every GridView and using a number index may not work all the time. Is there a way to get the cell using a string column reference??
This is what I figured out... I wrote a little function to get the index of the column based on the header text.
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);
}
}
The GetIndex method:
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;
}
If the column with that header text is there, then it will return the index. If not, then it will return -1 and you'll get an error... so some error handling is needed here if you don't know if the column is going to be there or not.
精彩评论