C# – Dynamically added user control event not firing

asp.netc

I saw that there are many similar question being asked. But in my case, I don't want add the user control on Page_Load nor OnInit. I would like to dynamically add user control to a PlaceHolder when a button on the page is clicked. I am able to load the control and it displays just fine. But the buttons in that user control wouldn't work. The event handler wouldn't fire. Worse than that, the whole user control would disappear after clicking the button in the user control.

Here is my user control which has a "RefreshButton" and its event handler simply updates the MessageLabel with DateTime.Now.

——————- TestUC.ascx ——————————

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TestUC.ascx.cs" Inherits="PASS.Web.UserControls.TestUC" %>
TestUC: 
<asp:Label ID="MessageLabel" runat="server"></asp:Label>
<asp:Button ID="RefreshButton" runat="server" Text="Refresh" onclick="RefreshButton_Click" />

—————- TestUC.ascx.cs ——————————

protected void Page_Load(object sender, EventArgs e)
{ }

protected void RefreshButton_Click(object sender, EventArgs e)
{
    this.MessageLabel.Text = " Server Time: " + DateTime.Now.ToString();
}

The parent page has a AddButton and a place holder. An instance of TestUC.ascx is (supposed to be) created every time the AddButton is clicked.

———— Test.aspx —————-

<asp:Panel ID="DynamicUserControlPanel" runat="server">
        <asp:Button ID="AddButton" runat="server"Text="Add New User Control Dynamically" onclick="AddButton_Click" />
        <asp:Panel ID="PlaceHolder" runat="server"></asp:Panel>
</asp:Panel>

———– Test.aspx.cs —————-

protected void AddButton_Click(object sender, EventArgs e)
    {
        UserControls.TestUC uc = LoadControl("~/UserControls/TestUC.ascx") as UserControls.TestUC;
        uc.ID = RandomStringGenerator.Generate(10);
        this.PlaceHolder.Controls.Add(uc);
    }

First of all, when AddButton is clicked (and keep being clicked), only one instance of TestUC.ascx is added and displayed. Secondly, the RefreshButton in the user control wouldn't fire. Thirdly, the user control would disappear when RefreshButton is clicked.

Is the idea of dynamically adding user control on button click feasible at all? Can someone please provide a simply example for achieving that?

Thank you very much in advance.

Best Answer

I don't want add the user control on Page_Load nor OnInit

Then your code won't work.

You need to recreate the controls on every post. I have demonstration code to accomplish this:

Note. In this example, the user controls are being added dynamically to the page on demand, when a user press a button and all events work.

Output

enter image description here

Code behind

    protected void Page_Init(object sender, EventArgs e)
    {
        for (int i = 0; i < this.DynamicControlsCount; i++)
        {
            var c = this.LoadControl("~/AddressControl.ascx");

            this.addresses.Controls.Add(c);
        }
    }

    protected void addAddress_Click(object sender, EventArgs e)
    {
        this.DynamicControlsCount++;
        var c = this.LoadControl("~/AddressControl.ascx");

        this.addresses.Controls.Add(c);
    }

    protected int DynamicControlsCount
    {
        get
        {
            if (string.IsNullOrWhiteSpace(this.Request.Form["numberOfControls"]))
            {
                return 0;
            }
            return int.Parse(this.Request.Form["numberOfControls"]);
        }
        set
        {
            int temp = int.Parse(this.numberOfControls.Value);
            temp++;
            this.numberOfControls.Value = temp.ToString();
        }
    }

ASPX

    <asp:PlaceHolder runat="server" ID="addresses" /><br />
    <asp:HiddenField runat="server" ID="numberOfControls" Value="0" />
    <asp:Button Text="Add Address" runat="server" ID="addAddress" OnClick="addAddress_Click" />
Related Topic