How to reference a ListBox name using a string in Csharp

400 Views Asked by At
for (int i=1; i<4; i++)
{
    string buttonName = "button" + i;
    if (Controls[buttonName].BackColor = Color.Red)
    {
        Controls[buttonName].Enabled = false;
    }
}

This code works perfectly. The code checks 3 different buttons (button1, button2, button3) and if their color is red they become disabled. The button name is referenced using a string:

Controls[buttonName]

Is there a way to reference a ListBox using a string in the same way? What would "Controls" need to be changed to?

1

There are 1 best solutions below

1
Filburt On

If you simply want to go over all ListBoxes, you could also use .OfType<T>()

foreach (ListBox lb in this.Controls.OfType<ListBox>())
{
    lb.Enabled = false;
}

... and it would of course work the same for .OfType<Button>() without the need to name your controls in a way to enumerate them.