LCJ
LCJ

Reputation: 22652

Can button click event handler be invoked before Page_Load?

I have following code that has Page Load event handler and a button click event handler. The Page Load handler is invoked before button click as expected in Page Life Cycle.

Is there any scenario in which Button Click handler will be called prior to Page Load handler ? (Due to some validation control or so).

If it is guaranteed that the Page_Load will be called always, I need not call the MyGetCount() function inside the button click handler.

public partial class WebForm1 : System.Web.UI.Page
{

    int tableDataCount = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
        string val = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
        //Get the count inside page load
        tableDataCount = MyGetCount();
    }

    protected void btnAction_Click(object sender, EventArgs e)
    {
        Response.Write(tableDataCount.ToString());
    }

    private int MyGetCount()
    {
        int count = 135;
        //Logic for count
        return count;
    }

}

Upvotes: 0

Views: 1444

Answers (3)

EdSF
EdSF

Reputation: 12351

"any scenario"? Not in the ASP.Net postback/page life cycle scenario as stated by all the answers, but since you've asked "any", you can try (re-writing and) exposing your method to client side script.

Although this isn't really about the "handler" or event, it's about the method....

Just a thought....

Upvotes: 0

Jack
Jack

Reputation: 761

there is no scenario where button click handler is called before page-load and that is not possible also. It is in page load that all controls are initialized it is only then the event handlers for the controls can be invoked.

Upvotes: 1

Andrei
Andrei

Reputation: 56688

It is guaranteed. Control event handlers are always called after the page loading phase is completed. For reference check out this MSDN article.

Upvotes: 4

Related Questions