Asp Dot Net Notes for Web Masters RSS 2.0

# Monday, January 03, 2011

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:
  1. Include in-line 'Code Blocks' into your page/user control. E.G. <% Response.Write("Hello"); %>
  2. 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.
Monday, January 03, 2011 12:13:47 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
Asp.Net Errors
Archive
<January 2011>
SunMonTueWedThuFriSat
2627282930311
2345678
9101112131415
16171819202122
23242526272829
303112345
Blogroll
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2012
I do I.T. Ltd.
Sign In
Statistics
Total Posts: 27
This Year: 0
This Month: 0
This Week: 0
Comments: 21
All Content © 2012, I do I.T. Ltd.