且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

System.Web.HttpException: 类型“TextBox”的控件“ctl02_TextBox2”必须放在具有 runat=server 的窗体标记内。

更新时间:2022-09-22 08:47:43

目的:加入用户自定义控件 
错误提示: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> &nbsp; 
<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> 
                &nbsp; </div> 
        </form> 
</body> 
</html> 

.aspx.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   User_Control   :   System.Web.UI.Page 

        protected   void   Page_Load(object   sender,   EventArgs   e) 
        { 
                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,如需转载请自行联系原作者