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.