BrunoLM
BrunoLM

Reputation: 100331

Using LoadControl without a Page

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" />

Upvotes: 8

Views: 3895

Answers (3)

Alex R
Alex R

Reputation: 301

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

(Page ?? new Page()).LoadControl(...)

Upvotes: 3

Tim Schmelter
Tim Schmelter

Reputation: 460108

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
}

Upvotes: 14

MisterZimbu
MisterZimbu

Reputation: 2713

LoadControl isn't a method of Page, it's a method of the Control class.

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

Upvotes: -1

Related Questions