ASP.NET动态添加用户控件的方法
程序员文章站
2023-12-22 08:10:40
本文实例讲述了asp.net动态添加用户控件的方法。分享给大家供大家参考。具体实现方法如下:
为了让用户控件能asp.net页面实现动态添加,首先写一个接口igetuca...
本文实例讲述了asp.net动态添加用户控件的方法。分享给大家供大家参考。具体实现方法如下:
为了让用户控件能asp.net页面实现动态添加,首先写一个接口igetucable,这个接口有一个函数,返回对象类型是usercontrol.
using system; using system.collections.generic; using system.linq; using system.web; using system.web.ui; /// <summary> /// summary description for igetucable /// </summary> namespace insus.net { public interface igetucable { usercontrol getuc(); } }
有了接口之后,需要创建用户控件calculator.ascx:
<%@ control language="c#" autoeventwireup="true" codefile="calculator.ascx.cs" inherits="calculator" %> number a: <asp:textbox id="textbox1" runat="server"></asp:textbox> <br /> + <br /> number b: <asp:textbox id="textbox2" runat="server"></asp:textbox><br /> <asp:button id="buttonequal" runat="server" text="=" onclick="buttonequal_click1" /> <br /> result: <asp:label id="labelresult" runat="server" text=""></asp:label>
calculator.ascx.cs,cs实现接口:
using system; using system.collections.generic; using system.linq; using system.web; using system.web.ui; using system.web.ui.webcontrols; using insus.net; public partial class calculator : system.web.ui.usercontrol,igetucable { protected void page_load(object sender, eventargs e) { } protected void buttonequal_click1(object sender, eventargs e) { decimal a = decimal.parse(this.textbox1.text.trim()); decimal b = decimal.parse(this.textbox2.text.trim()); this.labelresult.text = (a + b)。tostring (); } public usercontrol getuc() { return this; } }
最后是在需要加载用户控件的aspx的page_load事件写:
protected void page_load(object sender, eventargs e) { igetucable uc1 = (igetucable)loadcontrol("~/calculator.ascx"); this.form1.controls.add(uc1.getuc()); }
希望本文所述对大家的asp.net程序设计有所帮助。