c# - Event handler for a dynamically added button -
code :
public partial class form3 : form { ... ... private void button1_click(object sender, eventargs e) { panel p = new panel(); textbox diaryname = new textbox(); button b = new button(); label l = new label(); diaryname.font = new font("consolas", 12, fontstyle.bold); b.font = buttonfont; l.font = buttonfont; b.backcolor = color.wheat; l.text = "diary name : "; b.text = "add diary"; point lbl = l.location; diaryname.location = new point(l.location.x + l.width + 5, lbl.y); point txtbox = diaryname.location; b.location = new point(txtbox.x + diaryname.width + 20, txtbox.y); p.controls.add(l); p.controls.add(diaryname); p.controls.add(b); p.location = new point(12,272); p.size = new size(20 + 20 + 20 + diaryname.width + l.width + b.width, diaryname.height); // need help here.. // b.click += new eventhandler(); ??? this.controls.add(p); this.height += 50; this.width += 30; this.formborderstyle = formborderstyle.fixed3d; } ... } the above code adds panel contains label,a textbox , button form , that's working fine, problem want handle click event of dynamically added button (b) , in event handling code should able access dynamically added textbox (diaryname) validation purposes, don't know how it. tried adding function within same class form3 , since textbox t created within button1_click function, unable access textbox , how can around ?
i new c#, have java background there way in c# declare event handlers this
button.addactionlistener(new actionlistener() { public void actionperformed(actionevent e) { system.out.println("you clicked button"); } });
you can easy assign handler button's event way:
b.click += new eventhandler(newbuttonclick); where
protected void newbuttonclick(object sender, eventargs e) { //access textbox var mytextbox = this.controls.oftype<textbox>().firstordefault(tb=>tb.name == "diaryname"); if(mytextbox!=null) { //rest of code here } } however it's poor practice. button depend heavily on objects created dynamically somewhere outside - breaks encapsulation rule of oop. secondly - did think happen if you'll click original button (the 1 showed handler for) twice?
edit: when i've come think it, method not dynamic really. creates controls on fly, they're not generic in way - it's static piece of code, creates same result. in case i'd think putting new panel, textbox , button in form public items , initialize them within method. it'd improve create them in visual studio's designer already, hide them using visible properties , in button1_click alter sizes , show them up.
c# event-handling
No comments:
Post a Comment