tags:

views:

42

answers:

2

How can I dynamically load a usercontrol in ASP.NET if I dont have access to a Page object (say I'm in a utility class)?

Normally you would do :

Page.LoadControl("~/controls/MyControl.ascx");
+1  A: 

The only way to load a user control properly (that is to say in a way that will initiate its life-cycle) is to add it to the control collection of another control.

So you will either need to pass in a reference to the page or a reference to a control that is on the page and add the control to that control's collection.

Andrew Hare
+2  A: 

You could add a control from your utility class to the current page, using the following code:

Page currentPage = HttpContext.Current.Handler as Page;
if (currentPage != null)
{
    currentPage.Controls.Add(
        currentPage.LoadControl("~/controls/MyControl.ascx"));
}

It works, but I would not recommend this and consider it a hack.

M4N
not too hacky! i've seen worse
Simon_Weaver
So have I. That's actually a nicer solution than some things I've done.
DannySmurf
in my case i'm returning the control and it is added to a placeholder further up the callstack. i see here youre adding it to the page directly which would defintiely be very hacky and obviously probably not be of much use
Simon_Weaver
Yes, it probably depends on the actual situation how hacky it is :-)
M4N