Friday, July 20, 2007

Befuddling Error: "The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases."

If you ever modify the controls collection (e.g. myControl.Controls.Add()) of a parent control, such as the Page, inside a UserControl you my have seen the following error.

"The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases."



Unfortunately, this error is a bit obtuse, since we can most certainly modify the controls collection in event handlers that take place during those phases. So, what should we divine from this error message? It helps to remember this error is being thrown by the control collection that the current control is contained in, or another level up in the controls collections hierarchy.



My understanding is that you can modify down, not up, in the controls hierarchy. In other words, if you want to add a control dynamically to your parent, the parent needs to have a place to put it. The solution is to add a PlaceHolder control to the parent, then add your controls dynamically to that PlaceHolder.

5 comments:

Plasma said...

I hit this problem myself and found the solution I was after.

You may also want to look in to applying the INamingContainer interface to the control you are moving around, this lets it move within the hierarchy (and its children go with it).

ashish kumar said...

can I remove a control from the page's control collection on init event handler of the usercontrol of the same page
page
---control1
---usercontrol1

now I want to remove control1 in Init event handler of usercontrol1

throwing the same error
any suggestion

Scott MacMaster said...

Were you getting this error at runtime or in the designer? I just get this error but only in the designer but not until I put my custom control in an UpdatePanel. After, searching the web I couldn't find a solution that worked. I then tried commenting code in my custom control until the error went away. Eventually, I found the code that was causing the error. My custom control adds javascript and css into the page header. So I used 'if DesignMode = false' to skip doing that in the designer and the error went away.

Uday said...

@Scott : Thank You. Very helpful post.

Renadeen said...

Thank you! The only post in google that explained me the cause of problem.
As workaround I used deferred adding of control:
//in child control code
Page.PreRenderComplete += (sender, args) => newParent.Controls.Add(this);