I would like to be able to control the visibility of GridView
columns in the code-behind using a unique identifier that I assign. This way, I can dynamically decide which columns to show and hide, and I don't have to change the code every time I add a new column.
The best way I've thought of to do this is use the HeaderText
of columns as unique identifiers, and create a function that loops over all the DataControlField
objects in GridView.Columns
, searching for the requested HeaderText.
It seems strange to me though that DataControlField
objects couldn't have an assignable ID property that could be accessed like GridView.Columns["AssignableID"]
. Is there a programmatic reason that DataControlField
cannot have an ID property that works this way, or is it just a functionality that doesn't happen to exist?
My question is more about the reason why it doesn't exist than an actual solution to the hiding columns problem, though if someone has a better method for accomplishing this I would appreciate it.
Per request, here is an example of searching by HeaderText:
protected DataControlField GetColumn(GridView grid, string columnName)
{
foreach (DataControlField column in grid.Columns)
{
if (column.HeaderText == columnName)
{
return column;
}
}
return null;
}