Dynamically added control event does not fire

Dynamically added control event does not fire. This happens in the function called in the event for creating children on the page.

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

      

+2


source to share


4 answers


Asp.net pages have lifecyle . The event is dispatched based on the management tree. Your dynamic control should be in a management tree. Add the control to a placeholder on your page's OnInit or Onload or with the control and the event will be dispatched.



+1


source


You need to place it in an earlier event. Try putting your code in your init event handler.



0


source


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

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

      

However, since the Page_Load fires before the button click handler, if you cannot create the button during the postback, then the button will not exist at the time of its event.

0


source


Putting the code in an earlier event won't solve the problem. Even if you try to put your code in Page_Load () won't solve the problem.

As per the page lifecycle, try overriding the OnLoad function and re-creating and re-connecting the dynamically generated 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)
{
}

      

0


source







All Articles