为了让用户控件能ASPNET页面实现动态添加首先写一个接口IGetUCable这个接口有一个函数返回对象类型是UserControl View Code using System; using SystemCollectionsGeneric; using SystemLinq; using SystemWeb; using SystemWebUI; /// <summary> /// Summary description for IGetUCable /// </summary> namespace InsusNET { public interface IGetUCable { UserControl GetUC() } } 有了接口之后需要创建用户控件Calculatorascx: View Code <%@ Control Language=C# AutoEventWireup=true CodeFile=Calculatorascxcs Inherits=Calculator %> Number A: <asp:TextBox ID=TextBox runat=server></asp:TextBox> <br /> + <br /> Number B: <asp:TextBox ID=TextBox runat=server></asp:TextBox><br /> <asp:Button ID=ButtonEqual runat=server Text== OnClick=ButtonEqual_Click /> <br /> Result: <asp:Label ID=LabelResult runat=server Text=></asp:Label> Calculatorascxcscs实现接口 View Code using System; using SystemCollectionsGeneric; using SystemLinq; using SystemWeb; using SystemWebUI; using SystemWebUIWebControls; using InsusNET; public partial class Calculator : SystemWebUIUserControlIGetUCable { protected void Page_Load(object sender EventArgs e) { } protected void ButtonEqual_Click(object sender EventArgs e) { decimal a = decimalParse(thisTextBoxTextTrim()) decimal b = decimalParse(thisTextBoxTextTrim()) thisLabelResultText = (a + b)ToString () } public UserControl GetUC() { return this; } } 最后是在需要加载用户控件的aspx的Page_load事件写 View Code protected void Page_Load(object sender EventArgs e) { IGetUCable uc = (IGetUCable)LoadControl(~/Calculatorascx) thisformControlsAdd(ucGetUC()) } 用户控件加载之后运行效果 |