熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

動態添加用戶控件

2022-06-13   來源: .NET編程 

  為了讓用戶控件能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())
   
    }
   
    用戶控件加載之後運行效果

  \



From:http://tw.wingwit.com/Article/program/net/201311/13440.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.