August 15, 2007

WORKAROUND: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

Issue

ASP.NET 2.0: You are trying to add a control to a page where you are using code blocks (<% ... %> or <%= ... %>). When you do, an exception is thrown with the message "The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)."

Workaround

The easiest workaround is to drop a PlaceHolder control where you want to add your new controls, then add the control to the placeholder instead of to the page directly. This works in the body as well as headers.

Because we use master pages and only add controls to the header in two locations, I dropped a PlaceHolder control in my header called "HeaderAddIns" and I call a helper function to add literals to my header as necessary...
public static void AddControlToHeader(Page p, Control c)
{
PlaceHolder ph = p.Header.FindControl("HeaderAddIns") as PlaceHolder;
if (ph != null) ph.Controls.Add(c);
}


For other workarounds, check out this article on Rick Strahl's blog.

No comments: