views:

514

answers:

2

I have a usercontrol that move dynamically on the CreateChildControls method some web controls. When using this control into a page like :

<myControls:MyUserControl runat="server" ID="myUserControl" />

It works flawlessly.

But if I want to add that userControl dynamically into a page like :

<asp:UpdatePanel runat="server">
    <ContentTemplate>
        <asp:PlaceHolder runat="server" ID="plhControls" />
    </ContentTemplate>
</asp:UpdatePanel>
<asp:Button runat="server" ID="btnAdd" OnClick="btnAdd_Click" />

.cs

protected void btnAdd_Click(object sender, EventArgs e)
{
    MyUserControl myUserControl =(MyUserControl)LoadControl("~/Controls/MyUserControl.ascx");
    myUserControl.ID = "test";
    plhControls.Controls.Add(myUserControl );
}

It crashes inside my CreateChildControls with error : The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases.

The exact line is when I add the webControls to the placeholder inside my UserControl :

plhContent.Controls.Add(myWebControl);

So I don't understand why in this case I cannot move a web control inside the CreateChildControls event when I add my UserControl dynamically.

A: 

The controls have to be initialised and brought up to speed with the rest of the controls as far as the "page lifecycle" is concerned. Have a look at the Page.LoadControl method, and see if it's possible to create your control earlier on.

The method we sometimes use involves using a postback parameter from the page. Don't forget that you will need to re-add your control to the form fot every postback, as it will not get created for you

Matthew Steeples
Unfortunately, I cannot create my control earlier, because of a prior control move. and therefor I cannot use parameters for postback.
lucian.jp
A: 

Since LoadControl catch up every event of the loaded control to the current event, it is impossible to run the CreateChildControls at the same time as the parent since the event already occurred ed at that time.

In my case I cannot add dynamically my UserControl, so I did the opposite to reproduce the same behaviour I wanted. I initialize all my controls, and remove those I don't want OnClick. This add unneeded load time, but it is acceptable in the scenario I use it.

lucian.jp