September 1, 2008 0

How To Load & Reference An Usercontrol From Code Behind

By J in Tags: ,

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

Tags: ,

Leave a Reply