tags:

views:

35

answers:

2

I have a form in which several buttons are added at runtime via a 'for' method

 public Form()
 {
 for (int i = 0 ... )
  Button b = new Button() 
  b.text =  (string) i ;
  etc..
  etc..
  }

. now i wish to change the text property of the buttons on a certain event. How can this be accomplished? I have tried a few things but none worked.. since the buttons variables are inside the method , they are not available outside.

Thanks

+4  A: 

The variables aren't important (although you could store them in a single List<T> field if it made things easier). The normal way to do this is to look through the Controls collection (recursively, if necessary).

foreach(Control control in someParent.Controls) {
    Button btn = control as Button;
    if(btn != null) {
        btn.Text = "hello world";
        // etc
    }
}

The above assumes all the buttons were added to the same parent control; if that isn't the case, then walk recursively:

void DoSomething(Control parent) {
    foreach(Control control in parent.Controls) {
        Button btn = control as Button;
        if(btn != null) {
            btn.Text = "hello world";
            // etc
        }
        DoSometing(control); // recurse
    }
}
Marc Gravell
That's it, that's how it should be done, +1 for the recursive version.
Darin Dimitrov
this code is a bit over my head, so i'll have to study this a bit. Thanks a lot!
@user257412 - the controls are in a tree; controls such as panels can have other controls inside them, and those could *also* be container controls. This code simply walks through the tree looking for the buttons. Of course, it would help if there was something obvious to identify *your* buttons (perhaps the `.Tag`).
Marc Gravell
A: 

You can keep the reference of the button you have created ie you can either have a List with all the dynamic controls in it or if it is only one button, make the button object a class level object so that you can access it anywhere.

danish