If you want to instantiate an instance of user control inside ASPX code behind page, you need to write user control declaration on Page_Load
event as follows:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(Object sender, EventArgs e)
{
Control control1 = LoadControl("UserControl.ascx");
Page.Controls.Add(control1);
}
}
Note that the user control ASCX file should be already created when executing LoadControl method.
Another way known to declare user controls programatically is using PlaceHolder
:
public partial class Default : System.Web.UI.Page
{
public PlaceHolder Placeholder1;
protected void Page_Load(Object sender, EventArgs e)
{
Control control1 = LoadControl("UserControl.ascx");
Placeholder1.Controls.Add(control1);
}
}
Depending on your need, PlaceHolder
places user controls on a container storing all server controls dynamically added into the page, where Page.Controls
directly inserts user control inside the page which more preferred for rendering HTML literal controls.