Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

dynamically add controls

Status
Not open for further replies.

passs

Programmer
Dec 29, 2003
170
RU
Hi everybody!

Does anybody know how ca I add a web control dynamically in my asp.net page, for example Button. And I have a method which should be assigned to this button as a click handler.
I tried to do following: btn.click += new EventHandler(this.MyMethod); in onInit method of my page and then in Render method to add this button to my form. It apeared but click event didn't work.
So the problem is with dynamic event assigning.
Any ideas?

Thank you,
Alex
 
Try:
Code:
Button btn = new Button(); 
btn.Click += new EventHandler(btn_Click); 
btn.ID = "Test"; 
btn.Text = "Test Button"; 
this.FindControl("Form1").Controls.Add(btn);

Event handler:
Code:
private void btn_Click(object sender, System.EventArgs e) 
{ 
 .. do stuff here ...

Jim
 
Hi Guys,

Thank you for your help!
jbenson001, your code works perfect. And really I had the same code, but I added this button to my form in Render method and in this case event handler doesn't work. I cannot understand why. When this string of code in Page_Load:
this.FindControl("Form1").Controls.Add(btn); - everything works perfect, when in Render then clicking on this button I got nothing:)

Thank you!
Alex
 
I forgot to mention that any controls you add dynamically needs to be done in the Page_Init event. This is due to viewstate. You can google many examples and more in depth explination.

Jim

Glad you got it working...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top