Currently I have some buttons on my Winform that need to be disabled/enabled at various points depending what the user clicks.
The first draft I made was
button1.Enabled = false;
button2.Enabled = false;
To disable 2 buttons, which is obviously a horrible way of doing this, as there are currently a lot more than 2 and possibly more to come as this is still in development. So I need to have a way of easily changing a selection of buttons on the form.
Then I came up with this
private enum Buttons { Button1, Button2 } // etc with all buttons - that are named :)
private void DisableButtons(params Buttons[] buttons)
{
foreach (Buttons button in buttons)
{
switch (button)
{
case Buttons.Button1:
button1.Enabled = false;
break;
case Buttons.Button2:
button2.Enabled = false;
break;
}
}
}
Which I still wasn’t overly happy with. I could scrap the switch-case and foreach for
private void DisableButtons(params Buttons[] buttons)
{
button1.Enabled = buttons.Contains(Buttons.Button1) ? false : true;
}
for each button but I just think there must be a better way.
Any ideas on how I could do this more efficiently?
Thanks
You can shorten your last code line to:
Alternative solution
Or you can use the Tag property of each button to set a enum value for each button.
Than you can do it for all buttons in a for loop: