R – Catching events from dynamically added ASP.NET User Controls

asp.netplaceholder-controluser-controls

I have an ASP.NET web form which I am adding a variable number User Controls to. I have two problems:

  1. The User Controls are added to a PlaceHolder on the form in the first PageLoad event (I only add them when "(!this.IsPostback)", but then when the form is posted back, the controls are gone. Is this normal? Since other controls on the form keep their state, I would expect these dynamically added ones to stay on the form as well. Do I have to add them for every postback?

  2. I also have a button and an event handler for the button click event, but this event handler is never called when I click on the button. Is there something special I have to do to catch events on dynamically added controls?

Best Answer

  1. Yes, you need to add them in every postback.
  2. Yes... the control needs to be in the control hierarchy before asp.net dispatches the event (i.e. create the dynamic controls as early in the page lifecycle as possible).
Related Topic