In this article I will explain with an example, how to resolve the following error: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)
 
 

Error

The following error occurs when you try to use the JavaScript for ASP.Net control which has the <% %> tags.
Server Error in 'ASP.Net' 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. <% ... %>).
 
 

Cause

If you use the following JavaScript code which has the <% %> tags to get the ClientID of the ASP.Net control.
Here, an ASP.Net Server tag is used to get the ClientID of TextBox hence cannot add controls dynamically to the HEAD section.
<head runat="server">
    <title></title>
    <script type="text/javascript"> 
        function GetValue() {
            var txt = document.getElementById("<%TextBox1.ClientID%>");
            alert(txt.value);
        }
    </script>
</head>
 
 

Solution

The solution to this problem is to remove the part which has server tags and place it somewhere else like in BODY section if you want to add dynamic controls from code behind.