Method of dynamically adding user controls by ASP.NET
- 2021-06-29 10:46:53
- OfStack
This article shows an example of how ASP.NET dynamically adds user controls.Share it for your reference.The implementation is as follows:
In order for the user control to dynamically add to the ASP.NET page, first write an interface IGetUCable, which has a function and the return object type is 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();
}
}
Once you have an 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 implements the 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, the Page_of aspx where the user control needs to be loadedload event write:
protected void Page_Load(object sender, EventArgs e)
{
IGetUCable uc1 = (IGetUCable)LoadControl("~/Calculator.ascx");
this.form1.Controls.Add(uc1.GetUC());
}
I hope that the description in this paper will be helpful to everyone's asp.net program design.