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");
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");
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.
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.