如何:以编程方式创建 ASP.NET 用户控件的实例

    技术2022-05-11  78

    就像能以编程方式在 ASP.NET 网页上创建任何服务器控件的实例一样,也能以同样方式创建用户控件的实例。以编程方式创建用户控件的实例在用户控件中,请确保 @ Control 指令包含将类分配给用户控件的 ClassName 属性。下面的示例对 ClassName 属性进行设置以强类型化用户控件。<%@ Control className="MyUserControl" %>在要使用该用户控件的页中,通过 @ Reference 指令创建对该用户控件的引用。当以编程方式创建用户控件时,只有创建了对该控件的引用之后,ASP.NET 网页才能使用该用户控件的强类型。例如,下面的代码创建对 MyUserControl.ascx 文件中所创建用户控件的引用。<%@ Reference Control="MyUserControl.ascx" %>注意打算以编程方式加载控件时,请使用 @ Reference。打算以声明方式向页添加用户控件时,请使用 @ Register 指令。有关详细信息,请参见如何:在 ASP.NET 网页中包括用户控件。使用用户控件的类名创建该控件的实例变量。该类将成为 ASP 命名空间的一部分。例如,如果希望创建声明为 Spinner 类的用户控件的实例,请使用如下所示的语法:C# 复制代码Protected ASP.Spinner Spinner1;通过在代码中调用 LoadControl 方法创建用户控件的实例。根据需要分配属性值,然后向页上容器的 ControlCollection 集合添加控件,如 PlaceHolder 控件。注意当使用 Add 方法向 ControlCollection 对象添加控件时,这些控件将按被处理的顺序放置在集合中。如果希望将控件添加到集合中的特定位置,请使用 AddAt 方法并指定要在其中存储该控件的索引位置。示例下面的示例演示一个以编程方式加载用户控件的 ASP.NET 网页。该页包含一个 @ Reference 指令,用于指定控件的文件。LoadControl 方法读取该文件并将其实例化为可添加到页的控件。 <% @ Page Language = " C# "   %> <% @ Reference Control = " ~/Controls/Spinner.ascx "   %> < script runat = " server " > private  ASP.Spinner Spinner1; protected   void  Page_Load( object  sender, EventArgs e) {    Spinner1 = (ASP.Spinner)LoadControl("~/Controls/Spinner.ascx");    // Set MaxValue first.    Spinner1.MaxValue = 20;    Spinner1.MinValue = 10;    PlaceHolder1.Controls.Add(Spinner1);} protected   void  Button1_Click( object  sender, EventArgs e) {    Label1.Text = Spinner1.CurrentNumber.ToString();} </ script > < html > < head id = " Head1 "  runat = " server " >    < title > Load User Control Programmatically </ title > </ head > < body >    < form id = " form1 "  runat = " server " >      < div >        < asp:PlaceHolder runat = server ID = " PlaceHolder1 "   />        < br  />        < asp:Button ID = " Button1 "  runat = " server "         Text = " Button "         OnClick = " Button1_Click "   />        < br  />        < br  />        < asp:Label ID = " Label1 "  runat = " server "  Text = "" ></ asp:Label >      </ div >    </ form > </ body > </ html >  

    最新回复(0)