ASP.NET Custom user control to add dynamically

What I have done is use the Page.LoadControl method in the Page_Init to add the custom user control to a place holder on the page.

protected void Page_Init(object sender, EventArgs e)
{
    //MyControl is the Custom User Control with a code behind file
    MyControl myControl = (MyControl)Page.LoadControl("~/MyControl.ascx");

    //UserControlHolder is a place holder on the aspx page
    // where I want to load the user control to
    UserControlHolder.Controls.Add(myControl);
}

This works fine for me.

Here is the code for the dynamically loaded user control:

MyControl.ascx.cs

public partial class MyControl : System.Web.UI.UserControl
{
    protected void Page_Init(object sender, EventArgs e)
    {
        LiteralControl lit = new LiteralControl("Test Literal Control");
        Page.Controls.Add(lit);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        whatever.Visible = true;

        if (IsPostBack)
        {
            whatever.Visible = false;
        }
    }
}

Leave a Comment