ASP.Net: System.Web.HttpException: The Controls collection cannot be modified because the control contains code blocks (i.e. <% … %>)

ASP.Net: System.Web.HttpException: The Controls collection cannot be modified because the control contains code blocks (i.e. <% … %>)

I got this error when I was working on a small AJAX demo project the other day. In this project I only have 1 TextBox controls and 1 AJAX CalendarExtender controls: one text box is for a begin date entry controlled by one CalendarExtender. I had a little javascript in head tag to do some popup work:



              <asp:Label ID="lblDate" runat="server" Text="Date (*):" Visible="False"></asp:Label></td><td>
                   
                      <asp:TextBox ID="txtDate" runat="server"   
                    ></asp:TextBox>
                    <asp:CalendarExtender ID="CalendarExtender1" runat="server" 
                        TargetControlID="txtDate">
                    </asp:CalendarExtender>

The scrip in head section was :


<script type="text/javascript" >
    function vinModal( i, j )
        {
  
     document.getElementById('<%=HiddenField1.ClientID %>').value = j;
     document.getElementById('<%=HiddenField2.ClientID %>').value = i;
     /*  document.getElementById('<%=lblPop.ClientID%>').innerHTML = "vinod";
       $find('ModalPopupExtender1').show();*/
     document.getElementById('<%=LinkButton1.ClientID%>').click();
    }
</script>

I was getting this error:

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. <% ... %>). 

Solution: I just put my javascript from head tag to just above form tag:

OK, now I kinda know what causes the error, though I don’t know exactly why it happens: the AJAX CalendarExtender will raise RegisterCssReferences function to inject some code into the section and will throw exception error if there are some code blocks (<% … %> (<% … %> in the section, either in a JavaScript function or

Comments