Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare a C# Web User Control but stop it from initializing?

I have a C#/ASP.NET .aspx page that declares two controls that each represents the content of one tab. I want a query string argument (e.g., ?tab=1) to determine which of the two controls is activated. My problem is, they both go through the initialization events and populate their child controls, wasting CPU resources and slowing the response time. Is it possible to deactivate them somehow so they don't go through any initialization?

My .aspx page looks like this:

<% if (TabId == 0)
   { %>
<my:usercontroltabone id="ctrl1" runat="server" />
<% }
   else if (TabId == 1)
   { %>
<my:usercontroltabtwo id="ctrl2" runat="server" />
<% } %>

And that part works fine. I assumed the that <%'s would have meant the control wouldn't actually be declared and so wouldn't initialize, but that isn't so...

like image 552
Scott Stafford Avatar asked Apr 02 '10 14:04

Scott Stafford


1 Answers

If inline/spaghetti server side code does not help, I can only think of one alternative solution: avoid declaring the controls in the markup. Instead, load the control you actually want on the page from your Page_Init event handler. The Page.LoadControl() method can be used for this:

void Page_Init(object sender, System.EventArgs e)
{
    Control tab;

    switch (TabId)
    {
        case 0: tab = LoadControl("usercontroltabone.ascx"); break;
        case 1: tab = LoadControl("usercontroltabtwo.ascx"); break;
        default: tab = LoadControl("defaulttab.ascx"); break;
    }

    somePlaceholder.Controls.Add(tab);
}
like image 77
Jørn Schou-Rode Avatar answered Nov 10 '22 15:11

Jørn Schou-Rode