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

3.3k Views Asked by At

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..

3

There are 3 best solutions below

1
On BEST ANSWER

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.

0
On

If you put them in a container of some sort, like a Panel or PlaceHolder, you can do something like this:

List<WebControl> ctrlList = PlaceHolder1.Controls.Cast<WebControl>().ToList();
foreach (WebControl ctrl in ctrlList)
{
    ctrl.Visible = false;
}

You can shorten the above example by doing this:

PlaceHolder1.Controls.Cast<WebControl>().ToList().ForEach(x => x.Visible = false);

If you wanted to, you could create properties that return lists of different types of controls:

public List<TextBox> InputList
{
    get
    {
        return PlaceHolder1.Controls.OfType<TextBox>().ToList();
    }
}
0
On

There are various ways to do this and depends on your specified project/needs.

You could wrap a group of items in a <asp:Panel> and then use the Children collection.

You could give the controls special ids like, group1_name, group2_name etc and loop the page's child control collection

You could add attributes to your controls like <asp:Button ... myGroup="1" /> and loop the Page's child controls then check the attributes.

You could add a base class and monitor the children collection and use the .Tag property to assign groups

and on and on...