ASP. NET Dynamic addition of user controls, asp.net controls
This example describes how to add a user control dynamically in ASP. NET. Share it with you for your reference. The specific implementation method is as follows:
To enable the user control to dynamically add ASP. NET pages, first write an interface IGetUCable, which has a function that returns the UserControl object type.
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();}}
With the interface, you need to create the user control 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 implementation interface:
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; }}
Finally, write in the Page_load event of the aspx that needs to load the user control:
protected void Page_Load(object sender, EventArgs e){ IGetUCable uc1 = (IGetUCable)LoadControl("~/Calculator.ascx"); this.form1.Controls.Add(uc1.GetUC());}
I hope this article will help you design your asp.net program.