c# - add text box dynamically and capture data on button click -
i adding text boxes dynamically , trying capture data entered in text box on button click. happening , though entered data in text box, when clicked button, page getting loaded , control getting created again. result , loosing data in text box. can tell me how can capture data entered dynamically created text boxes. sample code follows:
protected void page_load(object sender, eventargs e) { table tbltextboxes = new table(); for(int i=0;i<10;i++) { tablerow tr=new tablerow(); tablecell tc=new tablecell(); textbox tb=new textbox(); tb.id=i.tostring(); tc.controls.add(tb); tr.cells.add(tc); tablecell tc1=new tablecell(); linkbutton lnk=new linkbutton(); lnk.id=i.tostring()+tb.text+"lnk"; lnk.text = "show"; lnk.click+=new eventhandler(lnk_click); tc1.controls.add(lnk); tr.cells.add(tc1); tbltextboxes.rows.add(tr); } placetest.controls.add(tbltextboxes); } void lnk_click(object sender, eventargs e) { linkbutton lnk=sender linkbutton; label lbl=new label(); lbl.text="the text is"+lnk.id; placetest.controls.add(lbl); }
linkbutton id
changed every time enter text textbox
, post back.
one thing want make sure when creating control dynamically - want recreate them same id when post back.
updated solution (to retrieve text textbox)
protected void page_load(object sender, eventargs e) { var tbltextboxes = new table(); (int = 0; < 10; i++) { var tr = new tablerow(); var tc = new tablecell(); var tb = new textbox {id = i.tostring()}; tc.controls.add(tb); tr.cells.add(tc); var tc1 = new tablecell(); // fix - lnk.id=i.tostring()+tb.text+"lnk"; var lnk = new linkbutton {id = + "lnk", text = "show"}; lnk.click += lnk_click; tc1.controls.add(lnk); tr.cells.add(tc1); tbltextboxes.rows.add(tr); } placetest.controls.add(tbltextboxes); } void lnk_click(object sender, eventargs e) { var lnk = sender linkbutton; var lbl = new label(); lbl.text = "linkbutton id: " + lnk.id; // number value string string id = regex.replace(lnk.id, @"[^\d]", ""); // retrieves textbox control id var control = findcontrolrecursive(page, id); if (control != null) { var textbox = control textbox; lbl.text += "; textbox text: " + textbox.text; } placetest.controls.add(lbl); } public control findcontrolrecursive(control root, string id) { if (root.id == id) return root; return root.controls.cast<control>() .select(c => findcontrolrecursive(c, id)) .firstordefault(c => c != null); }
Comments
Post a Comment