views:

303

answers:

3

Event of dynamically added control is not fired. This happens in a function called in the create child controls event of the page.

Button bb = new Button();
bb.Click += new EventHandler(bb_Click);
PlaceHolderQuestions.Controls.Add(bb);
A: 

You need to put it in an earlier event. Try putting the code in the init event handler.

Kevin
the weird thing that it worked well in another page, but when i copied it and used in another page with some modification its not working!!
Ahmad Farid
put it at the init but it still didnt fire
Ahmad Farid
+1  A: 

Asp.net pages have a lifecyle. Event dispatching is done based on control tree. Your dynamic control should be in in the control tree. Add the control to the placeholder in OnInit or Onload of you page or containing control and the event will be dispatched.

Christian13467
the weird thing that it worked well in another page, but when i copied it and used in another page with some modification its not working!!
Ahmad Farid
Hmm. Check the property AutoEventWireUp="True|False" of your page. Maybe it is different set.
Christian13467
A: 

Ensure that this button is also dynamically created on each Page_Load. I often make the mistake of putting similar code inside of:

If Not Page.IsPostback()
  ...
End if

However since Page_Load fires before the handler for the button click, if you fail to create the button during a postback then the button does not 'exist' by the the time its event fires.

Corey Downie
i put it in the Page_Init and had this if condition but still not working
Ahmad Farid
No, you specifically want to put it _outside_ of this If condition.
Corey Downie