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.