Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LoadControl without a Page

Tags:

c#

asp.net

How can I 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" />
like image 676
BrunoLM Avatar asked Jul 22 '10 20:07

BrunoLM


2 Answers

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

Page page = HttpContext.Current.Handler as Page;
if (page != null)
{
     // Use page instance to load your Usercontrol
}
like image 165
Tim Schmelter Avatar answered Oct 14 '22 08:10

Tim Schmelter


You can always create a new instance of a page if you don't have one:

(Page ?? new Page()).LoadControl(...)
like image 30
Alex R Avatar answered Oct 14 '22 06:10

Alex R