How To Load & Reference An Usercontrol From Code Behind

First lets create a sample user control called MyControl for demonstration purposes

public partial class _Controls_MyControl : System.Web.UI.UserControl
{
    private string _myProperty;

    public string MyProperty
    {
        get { return _myProperty; }
        set { _myProperty = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

Now register this control in the web.config

<pages>
  <controls>
    <add tagPrefix="uc" tagName="MyControl" src="~/_Controls/MyControl.ascx"/>
  </controls>
</pages>

Now this is the most important part, you have to reference your user control in the .aspx page to be able to access its partial class members -

<%@ Reference Control="~/_Controls/MyControl.ascx" %>

Now finally lets instantiate and load the control from the code behind…

_Controls_MyControl myControl = (_Controls_MyControl)LoadControl("~/_Controls/MyControl.ascx");
myControl.MyProperty = "Hello World!!";
Page.Controls.Add(myControl);

That’s it

If you have any questions or comments, please post them below. If you liked this post, you can share it with your followers or follow me on Twitter!