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.
You need to make sure that the control is added during the
PreInitphase of the page’s life cycle. Basically, once theInitevent is raised, you shouldn’t modify what controls are in the page’s control collection.