Change properties of controls that were added at run time

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

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

. Now I want to change the text property of the buttons on a specific event. How can I do that? I tried a few things but no one worked. Because button variables are inside the method, they are not accessible from the outside.

thank

+3
source share
2 answers

Variables are not important (although you can save them in one field List<T>if this makes the task easier). The usual way to do this is to browse through the collection Controls(recursively, if necessary).

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

, ; , :

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
    }
}
+4

, , , , .

0

Source: https://habr.com/ru/post/1741641/


All Articles