views:

781

answers:

5

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?

A: 
  1. To achieve this, add your controls at page init instead of page load. (re-add at postback)
  2. You'll need to know the id of the buttons added to bind them to the event.
Eppz
I tried adding the controls in the PreInit stage, but then they disappear when I click on a button and it posts back. Also, in Robert C. Barth's answer below, he says you have to add them in every postback.
skb
+3  A: 
  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).
Robert C. Barth
A: 

1) You should add the controls on the Pre-init (Page life cycle)

2) You have to attach the event handler to the event of the created button.(events might occur much later in the page life cycle than the same events for controls created declaratively)

Quaky
A: 

I ran into a similar problem. I had a page that displayed a collection of custom web controls. My solution was to add an additional invisible web control so that when I clicked a button to add another control that I would just use the invisible one. Then on post back my load function would add another invisible control to the collection.

Distantsound
A: 

I figured out yesterday that you can actually make your app work like normal by loading the control tree right after the loadviewstateevent is fired. if you override the loadviewstate event, call mybase.loadviewstate and then put your own code to regenerate the controls right after it, the values for those controls will be available on page load. In one of my apps I use a viewstate field to hold the ID or the array info that can be used to recreate those controls.

Protected Overrides Sub LoadViewState(ByVal savedState As Object)
    MyBase.LoadViewState(savedState)
    If IsPostBack Then
        CreateMyControls()
    End If
End Sub
Middletone