Loading User Controls (ascx) from other User Controls

6.4k Views Asked by At

I have a UserControl (ascx) that, depending on the user's credentials, will load another UserControl (ascx). Currently the control to be loaded, contains a special navigation menu.

I am using this code:

UserControl jmNav = 
    (UserControl)Page.LoadControl("~/controls/client/jmNavigation.ascx");

Then, after some more code, I'm telling it to load, like this:

    SBarTopWelcome.Controls.Add(jmNav);

The problem is, that I'm getting an "object reference not set to instance of an object" error.

Yes, the path is correct - as I tried it like this, as well (in all variations):

UserControl jmNav = (UserControl)Page.LoadControl("/client/jmNavigation.ascx");

This one (and its variants) tells me it doesn't exist.

So! Any thoughts?

3

There are 3 best solutions below

0
On

HA! I'm such a DORK! I was declaring the "SideBarWelcome" within a control like this:

public Control sideBarTopWelcome
{
    get { return Page.FindControl("SideBarTopWelcome"); }
}

When I should have done it like this:

public Control sideBarTopWelcome
{
    get { return FindControl("SideBarTopWelcome"); }
}

Without Page. Thank you anyway, guys. I appreciate it.

1
On

One helpful solution is to add <%@ Register %> to your parent control. Yes, I know it's in your parent page, but it should also be in your control.

If you do this, you should be able to Strongly-Type your control. For example, a control with a class name of MyControl would be:

MyControl controlVar = (MyControl)this.LoadControl("MyControl.aspx");

If you are able to get the stronly-defined variable, you should have no problems.

7
On

Inside SideBar.ascx add a place holder named SideBarTopWelcomePlaceHolder.

<asp:PlaceHolder ID="SideBarTopWelcomePlaceHolder" runat="server"/>

Then load jmNavigation UserControl to SideBarTopWelcomePlaceHolder like this.

Control jmNav = 
    Control Page.LoadControl("~/controls/client/jmNavigation.ascx");
SideBarTopWelcomePlaceHolder.Add(jmNav);