mabeiyi
mabeiyi

Reputation: 367

onclick event of dynamically added button

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?

Upvotes: 2

Views: 1455

Answers (2)

Pankaj
Pankaj

Reputation: 10095

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.

  1. Add control at Runtime
  2. 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.

Upvotes: 0

Oded
Oded

Reputation: 498904

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?).

Upvotes: 4

Related Questions