Home > Blockchain >  How to loop through multiple Control.Controls
How to loop through multiple Control.Controls

Time:08-08

I need to loop through all the controls in all of my forms.

I'm doing this because I need to change some of their properties, including .BackColor

I tried doing:

List<ControlCollection> listOfAllFormControlCollections = new List<ControlCollection>(new ControlCollection[] {
      (ControlCollection)MachineProgrammer_form.instance.Controls,
      (ControlCollection)BuildMachines_form.instance.Controls,
      (ControlCollection)MainMenu_form.instance.Controls,
});

foreach (ControlCollection control in listOfAllFormControlCollections)
{
  control.BackColor= Color.Blue;
}

But this does not work.

How do I do this?

CodePudding user response:

Look at what you've done here:

ControlCollection control

You have declared the variable as type ControlCollection, so you obviously know what it is, but then you have named it control, as though that will magically turn it into a single control with a BackColor property. It won't. The object is a ControlCollection, i.e. a collection of controls. What do you usually do with a collection of objects if you want to affect each item? You loop over it, which you obviously already know because you already have such a loop.

If you have a collection of collections then you loop over the outer collection to access each inner collection, then loop over that inner collection to access each item. That's what you would do in the real world, e.g. if I gave you a number of boxes and each box contained a number of cans and I told you to put a price sticker on each can. The logic we apply in the real world is the same logic we apply when programming.

foreach (var controlCollection in listOfAllFormControlCollections)
{
    foreach (Control control in controlCollection)
    {
        control.BackColor = Color.Blue;
    }
}

This will fix the code you have but keep in mind that, based on the way you create the list, it's only going to affect the current instance of each form type. If the user closes one of those forms and then opens another of the same type then the new instance will not pick up the new colour. For that, you'd have to have stored that new Color value somewhere and have the form's constructor get that value and apply it to the new instance.

  • Related