Server Error in '/' Application.
The
Controls collection cannot be modified because the control contains code blocks
(i.e. <% ... %>).
Description: An unhandled
exception occurred during the execution of the current web request. Please
review the stack trace for more information about the error and where it
originated in the code.
Exception
Details: System.Web.HttpException: The Controls
collection cannot be modified because the control contains code blocks (i.e.
<% ... %>).
What Caused This Error
This is can be seen when you do
BOTH of the following on the
same page/user control:
- Include in-line 'Code Blocks' into your
page/user control. E.G. <% Response.Write("Hello"); %>
- Add A
user control to the page/user control in a programmatic manner. E.G. Using the
LoadControl() Method in the code behind.
What is happening?
The in-line 'Code Block' has modified the Control Collection
of the base control that you are working with. Also you are trying to add a control
using server code, But you are trying to add that control to the same
collection that you have already modified with the in-line 'Code Block'. ASP.NET complains and a error is thrown.
How To Fix
To fix this I have found all I have to do is to put a server
control around my in-line 'Code Blocks'. This means that my in-line 'Code
Blocks' are only modifying the Control Collection of the new Server Control that contains the code block and not
the main page or control that I am working on. You can use a div tag with
runat="server" as your server control. All Server Controls should also have an ID, so add that too.
E.G.
<div id="Div2" runat="server">
<% Response.Write("Hello");
%>
</div>
This simple action of moving the offending code block into a
server control fixes the error.
The Server control does not have to be a div. You could use
any HTML control with the runat="server" added or any asp control.