how to reference class type in a LoadControl call?

232 Views Asked by At

In this example for loading a user control dynamically, how do I declare "TimeDisplay"? Can this be done in the code behind, or is it done in the ascx page? This is an example from a book, I guess there are assumptions made as to where the code files are located relative to one another?

protected void Page_Load(object sender, EventArgs e) 
{ TimeDisplay ctrl = (TimeDisplay)Page.LoadControl("TimeDisplay.ascx"); 
PlaceHolder1.Controls.Add(ctrl); 
}
2

There are 2 best solutions below

1
On

You do need to add a reference to the control in your aspx page:

<%@ Reference Control="~/Controls_Path/TimeDisplay.ascx" %>
1
On

To declare the control in markup, you'll need to register the control in the page directive or in the web.config. Registering the controls in web.config is usually preferrable because you can use the control anywhere in the application.

Config method:

<pages>
    <controls>
        <add tagPrefix="uc1" src="~/controls/myusercontrol.ascx" tagName="myusercontrol" />
    </controls>
</pages>            

Page directive method:

<%@ Register TagPrefix="uc1" TagName="MyUserControl" Src="~/controls/myusercontrol.ascx" %>