I need to add onclick event to some dynamically added button, but when i click the button, the onclick event is not fired. I saw some solutions to this, like link which says I should create the controls and attach the event on page_init or page_load every time there is a request, but, will this make the website very slow if I have a lot of controls to add?
-
2Do you really mean asp-classic? This sounds like ASP.NET WEbForms.Matthew Nichols– Matthew Nichols2012-02-27 14:52:10 +00:00Commented Feb 27, 2012 at 14:52
2 Answers
Yes, you must recreate dynamic controls if you want to access them and have their events fire on postback.
If you have so many controls on a page that your site is slow, you have a design issue. Rethink your design so you do not have so many controls on one page (perhaps several pages/tabs?).
3 Comments
Allocate memory like below to button in
Init Page Event
Button b = new Button();
b.Click += new EventHandler(b_Click);
void b_Click(object sender, EventArgs e)
{
}
As told by @Oded, this approach can create Design issue.
When you have a Div like control IN YOUR PAGE which is supposed to consume this Button, then you can GIVE CSS styles to give it proper alignment and proper placement.
You have two option.
- Add control at Runtime
- Add control at Design Time
Definitely, site will go slow in case of many controls in both cases. As both options will take memory BUT, By End of the Page Life Cycle, all the controls will get disposed.