如何声明C#Web用户控件,但停止对其进行初始化? [英] How do I declare a C# Web User Control but stop it from initializing?

查看:153
本文介绍了如何声明C#Web用户控件,但停止对其进行初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C#/ASP.NET .aspx页,该页声明了两个控件,每个控件代表一个选项卡的内容.我想要一个查询字符串参数(例如?tab = 1)来确定两个控件中的哪个被激活.我的问题是,它们都经过初始化事件并填充其子控件,从而浪费CPU资源并减慢了响应时间.是否可以通过某种方式停用它们,以便它们不进行任何初始化?

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?

我的.aspx页面如下:

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...

推荐答案

如果内联/意大利面条式服务器端代码无济于事,我只能想到一个替代解决方案:避免在标记中声明控件 >.而是从Page_Init事件处理程序中将所需的控件加载到页面上. Page.LoadControl() 方法可以用于此:

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);
}

这篇关于如何声明C#Web用户控件,但停止对其进行初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆