Bad design is the father of invention

Rupendra Dhillon's ASP .Net weblog

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

I am pretty sure that any web developer would hate an exception that is hard to catch. One of those is the one which says “The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

In my case I got this exception on a page that was working perfectly about two days ago and now had been untouched since then. My first line of Googling defense resulted in articles like this article and other discussions that tell you to change the <%= xxxxx %> to <%# xxxxx %>. Below I show how my code was when I was getting the error.

image

However just changing the <%= sign to <%# or moving the script tag within the content placeholder did not make any difference because even though it removed the original issue but caused another problem. The JavaScript wouldn’t load. :S

Here is my solution that resolves the issue and still lets the JavaScript load.

image

image

Just inject the script tag in a literal in the head of the master page in the code behind.

Digg This

Comments

AndrewSeven said:

Were you unable to determine who/what was trying to add a control and thus causing this error?

# June 26, 2009 9:24 AM

Cristovao Morgado said:

have you tried string.Format(".... {0}", AAAA);

I think it works

# June 26, 2009 12:36 PM

David Taylor said:

Hi,

Funny I had exactly this issue yesterday for the first time ever.

However I would say the exception message is perfectly clear and I figured out within a few minutes what to do.

# June 26, 2009 3:22 PM

rupendradhillon said:

To Andrew: The error was happening because the code snipped shown earlier was trying to dynamically inject javascript into the head of the page.

To David: Yes you are right that the exception message is pretty clear but this kind of an issue can be hard to catch when the probelm is on a master page which was being used for a lot of pages. (One of these pages was the one on which the issue was reported on). We had a lot of controls and a lot of code blocks in which the code that were of the form <%= %> and I had to go through a lot of checkins to find out that the issue is not in any control but how the javascript was made to load dynamically now.

# April 4, 2010 8:51 AM

rupendradhillon said:

To Andrew: The reason why this was done in the first page is that the since the pages that are using this materpage are at different locations in the website, the path to the JS file would be different for every page.

# April 4, 2010 8:54 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)