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

Once I was working in master page and wanted to call the javascript function that contains Code Blocks. Every time I got this error The Controls collection cannot be modified because the control contains code blocks (i.e. <% … %>). I was feeling headache to solve that error then one of my friend told me solution to get rid of this error and then every thing gone fine.

Actually I had an asp textbox control and an aspx button control in my masterpage, I wanted to get the value of <asp:TextBox id="txt_Name" runat="server"> in my javascript function but every time I got that error then I cut my javascript function from <head> </head> and put it into <form name="form1" runat="server"> of master page and then every thing worked fine.

You just have to put your javascript function in the form tag of master page

Here’s my javascript function

<form id="form1" runat="server">
<script type="text/javascript" language="javascript">

function FormValidation()
{
var my_Var;
my_Var=document.getElementById('<%=txt_Name.ClientID %>').value;

if(my_Var=="")
{
alert("Please enter the name");
return false;
}
else
{
return true;
}

}
</script>
</form>

Note:- The form attribute must contain runat="server" attribute.

So this is the way to avoid The Controls collection cannot be modified because the control contains code blocks (i.e. <% … %>) error.

Happy Coding!

0 comments: