The Controls collection cannot be modified because the control contains code blocks (i.e. <% … %> ) when adding the controls dynamically having Masterpages
I am trying to add an HiddenField control to the aspx page. I am getting the below mentioned error
The Controls collection cannot be modified because the control contains code blocks (i.e. <% … %> ).
This happens when I have to add the controls dynamically. On the net, I found all the types of answers to add <%# instead of <%=. In my case this is not applicable at all.
Here is my code sample,
HiddenField hndGuid = new HiddenField();
_page.Form.Controls.Add(hndGuid);
any pointers?
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
namespace wwwroot.Common
{
public class GuidClass
{
public GuidClass()
{
//
// TODO: Add constructor logic here
//
}
private string guid;
public string Guid
{
get
{
return guid;
}
set
{
guid = value;
}
}
}
public class Myhandler : System.Web.UI.Page, IHttpModule
{
Page _page = null;
HiddenField hndGuid = null;
Queue<string> temp;
public Myhandler()
{
temp=new Queue<string>();
}
public new void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
}
void context_PreRequestHandlerExecute(object sender, EventArgs e)
{
System.Web.HttpContext _httpContext = System.Web.HttpContext.Current;
if (_httpContext != null)
{
_page = _httpContext.Handler as System.Web.UI.Page;
if (_page != null)
{
_page.Init += new EventHandler(_page_Init);
_page.Load += new EventHandler(_page_Load);
hndGuid = new HiddenField();
hndGuid.ID = "hndGuid";
}
else
{
return;
}
}
else
{
return;
}
}
void _page_Init(object sender, EventArgs e)
{
_page.Form.Controls.Add(hndGuid);
if (!_page.IsPostBack)
hndGuid.Value = Guid.NewGuid().ToString();
}
void _page_Load(object sender, EventArgs e)
{
GuidClass currentGuid =new GuidClass();
currentGuid.Guid = hndGuid.Value;
System.Web.HttpContext _httpContext = System.Web.HttpContext.Current;
if (temp.Contains<string>(currentGuid.Guid))
{
_httpContext.Items.Add("IsRefresh",true);
}
else
{
if(!(currentGuid.Guid.Equals(null)||currentGuid.Guid.Equals("")))
temp.Enqueue(currentGuid.Guid);
_httpContext.Items.Add("IsRefresh",false);
}
}
}
}