2011-08-22 61 views
0

Controls集合無法修改,因爲控件包含動態添加控件時的代碼塊(即<%...%>)有MasterpagesControls集合不能被修改,因爲控件包含代碼塊(即<% … %>)動態添加具有Masterpages的控件

我想添加一個HiddenField控件到aspx頁面。我收到下面提到的錯誤

控件集合無法修改,因爲控件包含代碼塊(即<%...%>)。

發生這種情況時,我必須動態地添加控件。在網上,我發現所有類型的答案添加<%#而不是<%=。在我的情況下,這根本不適用。

這裏是我的代碼示例,

HiddenField hndGuid = new HiddenField(); 
_page.Form.Controls.Add(hndGuid); 

任何指針?

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); 
     } 
    } 
    } 
} 
+1

請提供到相關的標誌的建立代碼也。 –

+0

http://stackoverflow.com/questions/778952/the-controls-collection-cannot-be-modified-because-the-control-contains-code-bl http://stackoverflow.com/questions/4995274/the-控制收集-不能待改性因爲最控制包含碼-BLO –

回答

相關問題