Search code examples
c#asp.netservercontrols

Grouping ASP.net server controls to modify properties without referencing them by name


I'm trying to dynamically set the Visible property of multiple boxes, panels, buttons etc. from my codebehind for an aspx page. I was wondering if there is a way to group server controls into some logical group so that you could do something like this pseudo-code:

foreach(c in controlgroup) {
    c.Visible = value
}

The reason being is that the page displays different kinds of options depending on an ID parameter in the URL. I have seen this question but I'm wondering if there's another way to do it than by using user controls?

Edit: It would be nice if I could set the group on the aspx page rather than having to still add each control manually..


Solution

  • Sure. You can group them by building a List<Control>, and then loop over it.

    var controlList = new List<Control>();
    controls.Add(someTextBox);
    controls.Add(someOtherTextBox);
    // etc.
    
    // elsewhere
    foreach (var control in controlList)
        control.Visible = false;
    

    Of course, if you were working on controls all held in a common container (form, panel, etc.), you could simply loop over its control collection.

    foreach (var control in theContainer.Controls)
        control.Visible = false;
    

    And in this trivial example, making the container itself invisible would do the job. Beyond these simple methods, there is not a way to group controls that I know of, but I'm not often dealing with the UI.