views:

70

answers:

2

Hi all. 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 like to do something like that;

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;
     }
}
+6  A: 

The best thing is frankly not to have 16 different variables to start with. Instead, have an array:

Button[] buttons = new Button[16];

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:

Button[] buttons = new Button[16];
for (int i = 0; i < 16; i++)
{
    buttons[i] = (Button) Controls["button" + (i + 1)];
}

and from then on you can use the buttons array...

Of course you could do this instead:

Button[] buttons = { button1, button2, button3, button4, button5, ... };
Jon Skeet
Thank you for your response. My buttons are in a windows form and each of them is created like distinct objects. how can I add those to the array?
EEE
@EEE: Why do you have to create them separately to start with? If you can start off with an array, that's likely to be the best option.
Jon Skeet
I think using "Controls["button" + (i + 1)]" is what I wanted. I didn't know to reach the controls like that. Thank you very much.
EEE
+1  A: 

You can easily do this by using the Controls()-Collection of the container:

foreach(Control ctrl in Me.Controls()) {
    if(ctrl.Name.Startswith("Button")) {
        //do something
    }
}

From this you can access each control in the container, also casting it to the different types and so checking for your condition.

Bobby

Bobby