C# – ASP.NET usercontrol: check if usercontrol is visible

asp.netc

My question is somewhat related to this thread: How to avoid Initialization of web user control inside aspx?

The UserControl should only be visible when a button is clicked.
So my usercontrol is set like this:

<example:usercontrol ID="idControl" runat="server" Visible="false" />
<asp:Button ID="showMyControl" runat="server" OnClick="ShowMyControl" /

And the usercontrol itself checks if he's visible:

protected void Page_Load( object sender, EventArgs e ) {
    // only execute if the user control is visible
    if ( this.Visible ) {
        ...
    }
}

When I click the button I'm setting the property Visible of the usercontrol to true but when the postback occurs the Visible-property in the Page_Load of the usercontrol is still set to false.

My UserControl is probably loaded first and the Visible-property is set afterwards?
Is there an easy way to resolve this?

Thanks in advance!

Best Answer

The Load event of your control, which is being handled by your Page_Load event handler method if I understand correctly, gets fired before the Click event of your button control. Therefore, when the Page_Load method checks this.Visible, the property has not yet been changed because the Click event handler has not yet executed.

For this reason, I think that checking the Visible property of your control would be more appropriate in the PreRender event instead of the Load event.

I'm guessing that you're doing some sort of data retrieval or something that you wish to avoid if the control is not visible. Unfortunately, this sort of issue regarding the page life-cycle and the order in which events fire is sort of a common issue to deal with in ASP.Net programming.

If all of your initialization code can easily be moved into the PreRender event, then great. Problem solved (hopefully). If not (i.e. you need something to happen before the PreRender), you may need to come up with some other mechanism to ensure that your code executes at the right time. For example, you could expose a "SetVisible" method on your control which sets the Visible property to true and then also executes whatever initialization logic is needed. The downside of this is that you can't really guarantee that some code won't just set your control's Visible property to true outside of the SetVisible method that you provide.

Another idea is to actually override the Visible property and perform your initialization logic whenever that property gets set to true.

Related Topic