This article teaches you how to dynamically Add User Controls.
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.
View Code
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:
View Code
<% @ 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:
View Code
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:
View Code
Protected void Page_Load (object sender, EventArgs e)
{
IGetUCable uc1 = (IGetUCable) LoadControl ("~ /Calculator. ascx ");
This. form1.Controls. Add (uc1.GetUC ());
}
Running effect after the user control is loaded:
From Insus. NET