I am attempting to conditionally hide columns in an asp:gridview based off selections of a checkboxlist. I have the below syntax, but this line
grdTest.Columns[othergrid5].Visible = item.Selected;
Is throwing an error of:
Index was out of range. Must be non-negative and less than the size of the collection. parameter name:index
What do I need to do to remedy?
protected void btnDoTheWork_Click(object sender, EventArgs e)
{
var columnname = string.Empty;
foreach (System.Web.UI.WebControls.ListItem item in cbxUno.Items)
{
columnname = item.Text;
var othergrid5 = GetColumnIndex(grdTest, columnname);
grdTest.Columns[othergrid5].Visible = item.Selected;
}
}
private int GetColumnIndex(GridView grid, string ColName)
{
foreach (DataControlField col in grid.Columns)
{
if (col.HeaderText.ToLower().Trim() == ColName.ToLower().Trim()) { return grid.Columns.IndexOf(col); }
}
return -1;
}