天天看點

System.Web.HttpException: 類型“TextBox”的控件“ctl02_TextBox2”必須放在具有 runat=server 的窗體标記内。

目的:加入使用者自定義控件 

錯誤提示:System.Web.HttpException:   類型“TextBox”的控件“ctl02_TextBox2”必須放在具有   runat=server   的窗體标記内。 

沒有ctl02_TextBox2這個控件啊? 

WebUserControl.ascx   代碼 

<%@   Control   Language= "C# "   AutoEventWireup= "true "   CodeFile= "WebUserControl.ascx.cs "   Inherits= "WebUserControl "   %> 

<asp:TextBox   ID= "TextBox2 "   Text= "tb2 "   runat= "server "> </asp:TextBox>   

<asp:Button   ID= "Button1 "   runat= "server "   Text= "Button "   /> 

<asp:TextBox   ID= "TextBox1 "   Text= "tb1 "   runat= "server "> </asp:TextBox> 

<asp:Button   ID= "Button2 "   runat= "server "   Text= "Button "   /> 

WebUserControl.ascx.cs代碼 

using   System; 

using   System.Data; 

using   System.Configuration; 

using   System.Collections; 

using   System.Web; 

using   System.Web.Security; 

using   System.Web.UI; 

using   System.Web.UI.WebControls; 

using   System.Web.UI.WebControls.WebParts; 

using   System.Web.UI.HtmlControls; 

public   partial   class   WebUserControl   :   System.Web.UI.UserControl 

        protected   void   Page_Load(object   sender,   EventArgs   e) 

        { 

                TextBox1.Text   =   "text1 "; 

                TextBox2.Text   =   "text2 "; 

        } 

.aspx代碼: 

<%@   Page   Language= "C# "   AutoEventWireup= "true "   CodeFile= "User_Control.aspx.cs "   Inherits= "User_Control "   %> 

<%@   Reference   Control= "~/WebUserControl.ascx "%> 

<!DOCTYPE   html   PUBLIC   "-//W3C//DTD   XHTML   1.0   Transitional//EN "   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> 

<html   xmlns= "http://www.w3.org/1999/xhtml "   > 

<head   runat= "server "> 

        <title> 無标題頁 </title> 

</head> 

<body> 

        <form   id= "form1 "   runat= "server "> 

        <div> 

                  </div> 

        </form> 

</body> 

</html> 

.aspx.cs代碼 

public   partial   class   User_Control   :   System.Web.UI.Page 

                UserControl   uc   =(UserControl)LoadControl( "WebUserControl.ascx "); 

                Page.Controls.Add(uc); 

}

================================================================

方案1:

public   override   void   VerifyRenderingInServerForm(Control   control){ 

方案2:

不能用Page.Controls,你使用者控件中的那些伺服器控件必須在一個runat=server的form中,是以得要加到form裡面 

this.FindControl( "form1 ").Controls.Add(LoadControl( "WebUserControl.ascx "));

本文轉自左正部落格園部落格,原文連結:http://www.cnblogs.com/soundcode/archive/2012/05/16/2504294.html,如需轉載請自行聯系原作者

繼續閱讀