Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net - Page_Load and Page_Init get called on each button click?

So I have absolutely no logic in my code. I have the two methods Page_Init & Page_Load

Both methods get called every time I click the button. It makes sense for Page_load to get called. But why does Page_Init get called every time?

protected void Page_Init(Object sender, EventArgs e)
{

}

protected void Page_Load(object sender, EventArgs e)
{

}

protected void Button1_Click1(object sender, EventArgs e)
{
    // Do something here
}
like image 292
aryaxt Avatar asked Sep 20 '11 04:09

aryaxt


People also ask

Is Page_Init called on postback?

Page_Init is definitely called on every page hit, postback or not, exactly the same as Page_Load .

How can check button click on page load in asp net?

If your code is reliant on the OnClick event, then you can put that particular code in the OnPageRender override (rather than in Page_Load), as it will fire after the OnClick event handler.

When viewstate is loaded in ASP net?

The Viewstate is actually loaded in the OnPreLoad event of the page,Just after the Page_InitComplete.

How to add page Load event in ASP net c#?

Load. The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded. The Load event of individual controls occurs after the Load event of the page.


1 Answers

I guess you are unaware of Page Life Cycle.

Page_Init will always be called on page creation and it is called before Page Load.

Pre Init is called then Init is called and then Pre Load and then Load and then Pre Render and then Render on almost every time postback happens.

You can do this trick if you are not on live server. Add

Trace ="true"

in Page directive that will show you complete page cycle.

Like this,

   <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" 
    Inherits="_Default" Trace="true"%>
like image 163
Adnan Bhatti Avatar answered Sep 30 '22 19:09

Adnan Bhatti