5

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
}
aryaxt
  • 76,198
  • 92
  • 293
  • 442
  • 1
    by default button click sends a post back to the server. Therefor the page lifecycle will start over every time. – CBRRacer Sep 20 '11 at 05:34

1 Answers1

9

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"%>
Adnan Bhatti
  • 3,410
  • 4
  • 25
  • 38
  • 3
    Here is a good rad on the life cycle, http://msdn.microsoft.com/en-us/library/ms178472.aspx – Orn Kristjansson Sep 20 '11 at 04:04
  • 1
    The link I liked best for little bit of Page Life cycle and thorough explanation of VIEWSTATE is by Scott Mitchell who is a consultant. http://msdn.microsoft.com/en-us/library/ms972976.aspx – Adnan Bhatti Sep 20 '11 at 04:47