技术开发 频道

Asp.net2.0加载用户控件的三种方法

    【IT168 技术文档】方法一: 直接拖放的用户控件

<!--这是某个aspx页-->
.....
<%@ Register Src="TestControl.ascx" TagName="TestControl" TagPrefix="MyControl" %>
.....
<MyControl:TestControl ID="TestControl1" runat="server" />
.....

    若TestControl.ascx控件中含有DoSomething方法,且访问级别为public,则我们可以在cs代码中这样直接调用该方法如下:

//cs
代码文件

....
TestControl1.DoSomething();
....

    方法二: 动态加载的用户控件

    对于通过Page.LoadControl()方法来动态加载的用户控件我们可以这样做:

//cs文件
.....
ASP.testcontrol_ascx TestControl1 = (ASP.testcontrol_ascx)Page.LoadControl
("TestControl.ascx");
TestControl1.DoSomething();

    方法三: 利用Page.Pase方法动态加载控件

    对于通过Page.ParseControl()方法来动态加载的用户控件我们可以这样做:

Control control = this.Page.ParseControl(@"<%@ Register 
Src=""TestControl
.ascx"" TagName=""TestControl"" TagPrefix=""MyControl"" %>                       <MyControl:TestControl ID=""TestControl1
runat=""server"" />");
 this.Page.Controls.Add(control);


0
相关文章