Using a LoadControl Without a Page

How to load a control without a page?

public void Something() { var ascx = /*LoadControl*/("my.ascx"); // being Page = null var ctl1 = ascx.Controls[0]; var ctl2 = ascx.Controls[1]; } 

my.ascx:

 <%@ Control Language="C#" %> <asp:Literal ID="ctl1" runat="server" /> <asp:Label ID="ctl2" runat="server" /> 
+7
source share
3 answers

You can get your Page-Object from an HttpContext this way:

 Page page = HttpContext.Current.Handler as Page; if (page != null) { // Use page instance to load your Usercontrol } 
+12
source share

You can always create a new instance of the page if you do not have it:

 (Page ?? new Page()).LoadControl(...) 
+3
source share

LoadControl is not a page method, it is a Control class method.

You can simply use LoadControl () in your control instead of Page.LoadControl ()

-one
source share

All Articles