Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Gridview Columns Do Not Have ID?

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;
}
like image 942
David Avatar asked Nov 03 '22 22:11

David


1 Answers

First, I'm right there with you. I also think that code like this

myGridView.Columns[0].Visible = false;

is less readable and more prone to errors than (pseudo-code):

myGridView.Columns["UserName"].Visible = false;

Hence your question why there's no ID property in DataControlField makes sense.

As i've already commented:

Explicitly declared column fields can be used in combination with automatically generated column fields. When both are used, explicitly declared column fields are rendered first, followed by the automatically generated column fields. Automatically generated column fields are not added to the Columns collection.

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.columns.aspx

I assume that above and the fact that there are different types of DataControlFields like TemplateField, BoundField or ButtonField were the reasons why there's no ID property since it wouldn't be predictable. Some of them are added manually(declaratively or programmatically), others might be added automatically(f.e. the ButtonFields, the ID would be auto generated), some are included in the Columns collection whereas others not and so on.

like image 192
Tim Schmelter Avatar answered Nov 11 '22 16:11

Tim Schmelter