开发者

How to stop the execution of UC at page load on Visible false

开发者 https://www.devze.com 2023-04-04 03:20 出处:网络
I am thinking to stop the execution of pageload if that UC has been set to Visible false at the container page. Right now I am upto the following logic

I am thinking to stop the execution of pageload if that UC has been set to Visible false at the container page. Right now I am upto the following logic

public class TestControl : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (this.Visible)
        {
            //do heavy operation

        }
    }
}

i.e I will check whether the开发者_StackOverflow社区 control is visible false or not in the Page load of UC, if true, then only do the operations there. Is there any other better way to do so? I have so many UC in my application. Is there some common logic to stop the execution of page load of UC if it is Visible false.


The Visible property of the Control class only determines if the Control is rendered, it has no effect on the rest of a control's life cycle though.

From MSDN:

If this property is false, the server control is not rendered. You should take this into account when organizing the layout of your page. If a container control is not rendered, any controls that it contains will not be rendered even if you set the Visible property of an individual control to true. [...]

This makes sense, because that way you can have invisible controls that still perform a certain action. You could also do this by just not putting any content into them, but they probably still will render some whitespace or newline. Setting Visible to false is the clean way to do it.

I don't think there is any better way to prevent the execution of code if the Control is not visible, but I think you're solution is clean enough.

As an alternative you could put your code into the OnPreRender event, which is only fired when the control is visible. But keep in mind that this is a later step in the Control Lifecycle.

public class TestControl : System.Web.UI.UserControl
{
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        // Your code here
    }
}


UserControl.dispose() stop firing the usercontrol page_load event.

0

精彩评论

暂无评论...
验证码 换一张
取 消