Reputation: 14764
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);
Upvotes: 2
Views: 2906
Reputation: 369
Putting the code in an earlier event wont solve the problem. Even if you try to put your code in Page_Load() wont solve the problem.
According to the page's life cycle try to override the OnLoad function and recreate and re-wire up your dynamically created controls with the same IDs.
protected override void OnLoad(EventArgs e)
{
Button bb = new Button() { ID = "myBtn" }
bb.Click += new EventHandler(bb_Click);
PlaceHolderQuestions.Controls.Add(bb);
base.OnLoad(e);
}
protected void Page_Load(object sender, EventArgs e)
{
}
Upvotes: 0
Reputation: 4769
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.
Upvotes: 0
Reputation: 5584
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.
Upvotes: 1
Reputation: 115420
You need to put it in an earlier event. Try putting the code in the init event handler.
Upvotes: 0