Programmatically creating button
-
I am creating a button, a textbox and a label control, when a linkbutton is clicked. I have assigned an event handler to the button, but when the button is clicked nothing happens and even the previous controls created, disappear
protected void LinkButton2_Click(object sender, EventArgs e) { TableRow row = new TableRow(); TableCell cell1 = new TableCell(); txt = new TextBox(); txt.Rows = 2; txt.Height = 40; txt.Width = 200; cell1.Controls.Add(txt); row.Controls.Add(cell1); btn = new Button(); btn.Text = "Submit"; btn.Click += new EventHandler(btn_Click); TableCell cell2 = new TableCell(); cell2.Controls.Add(btn); row.Controls.Add(cell2); lbl1 = new Label(); lbl1.Text = "Your Comments"; TableCell cell3 = new TableCell(); cell3.Controls.Add(lbl1); row.Controls.Add(cell3); Table1.Controls.Add(row); } void btn_Click(object sender, EventArgs e) { //Does not reach here }
-
I am creating a button, a textbox and a label control, when a linkbutton is clicked. I have assigned an event handler to the button, but when the button is clicked nothing happens and even the previous controls created, disappear
protected void LinkButton2_Click(object sender, EventArgs e) { TableRow row = new TableRow(); TableCell cell1 = new TableCell(); txt = new TextBox(); txt.Rows = 2; txt.Height = 40; txt.Width = 200; cell1.Controls.Add(txt); row.Controls.Add(cell1); btn = new Button(); btn.Text = "Submit"; btn.Click += new EventHandler(btn_Click); TableCell cell2 = new TableCell(); cell2.Controls.Add(btn); row.Controls.Add(cell2); lbl1 = new Label(); lbl1.Text = "Your Comments"; TableCell cell3 = new TableCell(); cell3.Controls.Add(lbl1); row.Controls.Add(cell3); Table1.Controls.Add(row); } void btn_Click(object sender, EventArgs e) { //Does not reach here }
You need to create all dynamic control before page_Load, best to create them on
Page_PreInit
. Other wise the control will not able to maintainviewstate
andpostback
data. AsLoadPostBack
andLoadViewState
Fired before Page_Load.Abhijit Jana | Codeproject MVP Web Site : abhijitjana.net Don't forget to click "Good Answer" on the post(s) that helped you.
-
You need to create all dynamic control before page_Load, best to create them on
Page_PreInit
. Other wise the control will not able to maintainviewstate
andpostback
data. AsLoadPostBack
andLoadViewState
Fired before Page_Load.Abhijit Jana | Codeproject MVP Web Site : abhijitjana.net Don't forget to click "Good Answer" on the post(s) that helped you.
When recreating the controls in Page_PreInit, the line
Table1.Controls.Add(row);
gives an error.