views:

27

answers:

3

I'm trying to add a control in within a user control:

        LinkButton l = new LinkButton();
        l.Text = "Test";
        l.OnClientClick = "TestClick";
        l.ID = "TestID";
        l.Page = Page;
        Page.Controls.Add(l);

I get this error when the page loads:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

[InvalidOperationException: Collection was modified; enumeration operation may not execute.] System.Web.UI.ControlCollectionEnumerator.MoveNext() +8677726 System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +217 System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +8 System.Web.UI.Page.Render(HtmlTextWriter writer) +29 System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27 System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100 System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3060"

Am I simply not allowed to add controls to a page through code-behind when I'm in a custom web user control? The error does not happen if I don't add this control in.

+2  A: 

It is because you are adding it to the controls in the PAGE and not into your user control...

Your code will be called from the page, when the page is initializing its controls, and obviously at that point you wont be able to add additional control to the existing (partially initialised) control tree of the page...

Further, it is always prudent to add controls only to your user control than working with the controls in the page as you will not know, which page may end up using your control.

Try this:

 this.Controls.Add(l)
The King
+1  A: 

As far as I know you need to use a PlaceHolder Control if you want to add controls dynamically

More info here

Conrad Frix
The placeholder will help in determining where a control is rendered. It won't however make it safe to add controls too late in the page's life cycle.
jball
+2  A: 

You need to make sure that the control is added during the PreInit phase of the page's life cycle. Basically, once the Init event is raised, you shouldn't modify what controls are in the page's control collection.

jball
+1 Forgot about the PreInit bit.
Conrad Frix