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

While working with one if my applications where I was adding some controls to the head section of my page. Reason, I used the following JavaScript which had the <% %> tags to get the ClientID of a control

 

<head runat="server">

    <title>Untitled Page</title>

    <script type = "text/javascript">

        function GetValue()

        {

            var txt = document.getElementById("<%=TextBox1.ClientID%>");

            alert(txt.value);

        }

    </script>

</head>

 

As you can see above I have used ASP.Net Server tags to get the ClientID of textbox hence I cannot add controls dynamically to the head section

 

Solution

Remove the part which has server tags and place it somewhere else if you want to add dynamic controls from code behind

I removed my JavaScript from the head section of page and added it to the body of the page and got it working

If anyone else got some other solution that helped him please share