开发者

error when adding a control to a user control

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.

[开发者_Go百科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 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.


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)


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

More info here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜