winforms - Create button during runtime in C#.net? -


i know how create button during runtime.

button button1 = new button();  button1.location = new point(20,10); button1.text = "click me"; // adding groupbox1 groupbox1.controls.add(button1); 

but problem want add multiple buttons this..

for(int = 1; < 30; i++) { button button[i] = new button(); // button customization here... ... groupbox1.controls.add(button[i]);  } 

the code above false code. how can make happen true in c#.net? want create multiple buttons button name, button1, button2, button3, button4, .... button30;

you can't declare variables @ execution time in c# - don't want anyway, wouldn't able access them dynamically afterwards. create array:

// buttons declared button[] member variable buttons = new button[30];  for(int = 0; < buttons.length; i++) {     buttons[i] = new button();     // button customization here...     ...     groupbox1.controls.add(buttons[i]); } 

alternatively, use list<button>, more convenient if don't know how many buttons need beforehand. (see obligatory "arrays considered harmful" blog post.)

of course, if don't need @ buttons later, don't bother assigning them visible outside loop:

for(int = 0; < 30; i++) {     button button = new button();     // button customization here...     ...     groupbox1.controls.add(button); } 

you need think information need access when... , how want access it. if logically have collection of buttons, should use collection type variable (like list or array).

frankly think it's 1 of curses of vs designers end horrible names such "groupbox1" carry no information beyond what's in type declaration, , encourage developers think of collections of controls via individually-named variables. that's me being grumpy though :)


Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -