c# - How to add buttons with independent click event -


i want add buttons , textboxes dynamically on runtime each button react differently.

ie newbutton1 linked texbox1 ,newbutton2linked withtextbox2`

right button prints first last textbox 1 after other.

also consider have button1 & textbox1 on form guides

here code :

        list<button> buttons = new list<button>();         list<textbox> textboxes = new list<textbox>();          int numtextbox = 0;         void click(object sender, eventargs e)         {              messagebox.show(textboxes[numtextbox].text);             numtextbox++;         }          int x = 0;         int y = 0;         void addclick(object sender, eventargs e)         {                 button newbutton = new button();                 buttons.add(newbutton);                 newbutton.click += click;//                 // newbutton.location.y = button1.location.y + 20;                 newbutton.location = new point(button1.location.x, button1.location.y+25+x);                 x += 25;                 this.controls.add(newbutton);                     textbox newtextbox = new textbox();                 textboxes.add(newtextbox);                // newtextbox.click += click;                  newtextbox.location = new point(textbox1.location.x, textbox1.location.y+25+y);                 y += 25;                 this.controls.add(newtextbox);          } 

you can have class mybutton inherits button class, in new class can have property textbox type . following code . , in code when want instantiated button can use list<mybutton> , set linkedtextbox property textbox.

public class mybutton:button {    ...    public textbox linkedtextbox{set;get;} } 

and in code should write thing :

list<mybutton> buttons=new list<mybutton>(); textbox sometextbox=new textbox(); buttons[0].linkedtextbox=sometextbox; 

and in event can use:

((mybutton)sender).linkedtextbox.text="some thing"; 

Comments