I have 16 buttons named button1, button2… etc
What is the best way to iterate them and How do I need to store these buttons in( in an array or something)? I’d like to do something like the below:
public void func(string[] a)
{
for(int i = 0; i<16;i++)
{
if(a[i]==something)
button[i].image = someImage;
else
button[i].image = antoherImage;
}
}
The best thing is frankly not to have 16 different variables to start with. Instead, have an array:
Then you can use exactly the syntax you want (modulo the property name). The disadvantage is that the designer doesn’t really cater for this. Normally I find that if I need a lot of UI elements of the same type, it’s easier to create them programmatically than in the designer, but it depends on the situation.
Another option is to use
Controls["button" + (i + 1)], but that feels like a bit of a hack to me when you really just want an array. If you don’t ever need to reassign the variables, you could use:and from then on you can use the
buttonsarray…Of course you could do this instead: