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
All comments require the approval of the site owner before being displayed.
Name
E-mail
(will show your gravatar icon)
Home page

Comment (Some html is allowed: b, blockquote@cite, em, i, strike, strong, sub, sup, u) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview
Archive
<February 2012>
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
26272829123
45678910
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.