Monday, July 2, 2012

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


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

<head runat="server">
<title>Untitled Page</title>
<script type = "text/javascript">
function GetValue()
{
var txt = document.getElementById("<%=TextBox1.ClientID%>");
alert(txt.value);
}
</script>
</head>
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