Wednesday, September 19, 2012

Define page life cycle events with example in ASP .Net

Here You will get the solution of following queries:
Ques: What is page life cycle in asp .Net?
Ques: Describe events used in complete asp .net page life cycle.
Ques: Specify phase used in asp .Net page life cycle
Ques: Define Init, Load, Render and Unload events in page life cycle.

Today I want to share some knowledge about ASP .Net. Every developer who is working on ASP .Net must know about the Page life cycle[first step of web development using .Net technology]. Some of our friends after having 2-3 years of ASP .Net experience still don't have proper knowledge about all the events used in Page Life Cycle . As a developer I always got confused about page life cycle events in my beginning days, Here I am describing all the events with examples wherever applicable.

PreInit is the first phase in page life cycle events. This is the place where one can dynamically set their master page in the code. In such case you can also set any theme or skin to your page, in PreInit we can also set the properties of the server controls of Master page, like the code below:

protected void Page_PreInit(object sender, EventArgs e)
if (textBox1 == null)
          Response.Write("Pre Init, server control Not available");
          string TextinInit = textBox1.Text;
          Response.Write("Pre Init, Server Control enabled");

Page.MasterPageFile = "~/TestInitMaster.master";

       TextBox _mstTextBox = (TextBox)Page.Master.FindControl("txtMessage");
       Label _mstLabel = (Label)Page.Master.FindControl("lblMessage");

       _mstLabel.Text = "Setted in default page at time : " +ateTime.Now.ToString();
       _mstTextBox.Text = "Textbox set in default page";

In above you can see I’ve used a master page dynamically and set a label and TextBox’s Text property of that master page in runtime that means we can set the master page dynamically and associate the values in their controls if any. If you try to set the masterpage in any other event after Page_PreInit event, you will get an error message that will tell you that the master page only can be set on or before Page_PreInit event. In Page_PreInit event you can also see at the top level I’m checking a TextBox1 value whether it’s null or not. It is a server control (TextBox), but in PreInit the value will always be null of this text box or any other server control. So if I want to conclude the thing, in Page_PreInit controls are not fully initialized. So use this event for setting MasterPage file in your code. Each control Unique ID’s are also available at this event.

Init is called when you can initialize your page controls, this is the place that comes into picture after each Control initialization, till this event they get their Unique Id, master page etc. In Init you cannot access any controls properties after the last viewstate, I mean suppose you enter some text in a textbox control and click on a button control that makes a postback, now you want to view the value latest entered. In such case you will be able to see the textbox value which you’ve entered after the round trip happens, this is because of ViewState property of controls. That means they preserved your last saved value, but you see this value after Init phase because, usually we don’t use these events in our code and use just Page_Load event where the Viewstate value already got loaded. But as in Init phase, we cannot access our latest entered values in textbox, so in Init you won’t be able to get the latest changes. So I can say in Init we won’t be able to get the postback value.

In this event, Viewstate functionality is turned on for server control. Viewstate of controls allows preserving their values across postback.

This is the first event where viewstate functionality starts retrieving their values. PreLoad executes after InitComplete method. In this method, page has loaded values from viewstate. So for example in a button click event if you create a viewstate like below than what will going to be happen:

protected void btnSubmit_Click(object sender, EventArgs e)
            ViewState["myData"] = "just a text string";

After button click, postback will happen at it will start calling page events like PreInit, Init, Initcomplete. Till these three events you will not be able to get the value of Viewstate “myData”. Even when the event fires PreLoad event of page, at this time you cannot access the ViewState, this is because ViewState will set the value when reaches the ButtonClick event, and this will happen after Load event, so one more time we will click on our submit button, and because now the ViewState[“myData”] resides into my page, I can access it on my PreLoad event. For better understanding please see the screen shot below:
ASP .Net page life cycle

Most of the developers are familiar with the page load, as this is the only event that comes by default in aspx.cs page when you start doing anything with your code behind. The page Load events executes after the Page_PreLoad event. If you have created your own Load method in constructor of your code behing, then this will be the method that will execute before the Page_Load event and after Page_PreLoad event, for better understanding refer to the image below:
Init event in Page Life Cycle

As you are seeing in above code, I’ve created my own Page_Load event in my code behind as well as the default Load event, I didn’t mention Page_PreLoad event here, but it will execute after Page_InitComplete event. So back to the image, the _Default_Load will execute first before the Page_Load event. If you have any master page in your page, then the Load event of your master page will run followed by the user control Load event if they exist in your file.

After the Page_load the next event is Page Control’s event. For example, if you have a control that raises postback just like button, and you clicked on the Button, so after Page_Load your Button_Click event will fire, and do the rest of the thing you’ve mentioned in your page. for better understanding please refer to the image below, event execution will be happen in that sequence how image is showing, in event portion whatever you will do that will go ahead and will do the things you’ve mentioned in you page. just like below, I said to create a ViewState[“myData”] and put some string inside that viewstate. So now the viewstate is ready to preserve ahead in my code. 

In Events you can also check the Page.IsValid property if you’ve used any validator controls in your page like regularexpressionValidator, requiredFieldValidator, Range etc. To check this property refer to the image below.
Load complete event of Page Life Cycle

This event can be used when all the event processing has been done in the page.


PreRender event gets called when page has created all the controls that user will see in his browser. PreRenderComplete is the last place to change anything in the page. After this event any changes will not get preserved in page cycle. 

event gets fired immediately after the PreRenderComplete event, in this event the viewstate functionality and control state get saved, as I said in PreRenderComplete changes can be done that will affect the next postback. In SaveStateComplete you can do the changes in your server control, but the state won’t be available in next postbacks. 

Render is not an event but this is the phase where the HTML of your page will get rendered to the output stream with the help of HTMLTextWriter. You can override the Render method of page if you want to write your own code rather than the actual HTML text. As like below:

Render event of Page Life Cycle

As you can see in the code above, I’ve override the Render method in my code and write something with Heading 1 tag and later on called the base.render method. In current scenario the thing will happen is: apart my server controls code in my browser I’ll be able to see my Hello world text also. If I remove the base.render method calls, than I won’t be able to view my any control if I’ve created in page.

This is the last event that gets fired. This is the page cleaning process like closing the open file connections etc, so in this process you cannot do any kind of manipulation with data that affect the rendering, you are restricted to use Response property also, and doing such you will get an exception message.

There might be some mistakes with this article but I tried my best to share with you, So if you have some queries OR suggestions please feel free and share the by comment. Thank you for reading this post..


Anonymous said...

Nice Article... With good explanation...

Anonymous said...

Really Nice Artical, i Am getting impressed by you thanks

Anonymous said...

very good article....

Anonymous said...

Good article..

Anonymous said...

Good article.

Anonymous said...

yes this is very very nice example for events

Anonymous said...

This is the best tutorial on ASP.Net Page Life Cycle I have ever read.

Priyanka said...

Explaination with example way is very nice.Very helpful in understanding. After long time I could understand page life cycle. Thanks..

Anonymous said...

Impressed by reading this article.

Anonymous said...

Thanks for sharing.

Anonymous said...

thanks.. Nice work

Anonymous said...

Very gud article..I can't express my feeling...i have been strugling to understand the life cycle for few nw i understood..thanks a lot...

Anonymous said...

Botlhale J

Great tut with clear example... you are on point mate

Anonymous said...

sir in one of my interview they asked me like

what are the events are raised when button click ?????
can u please explain in order wise

Ankita Agrawal said...

The order of events raised on 'Botton Click' is given below-

1: Page.Init + Control.Init
2: Page.LoadViewState
3: Page.Load + Control.Load
4: Button.Click + Button.Command
5: Page.PreRender+Control.PreRender
6: Page.SaveViewState
7: Page.Render

Dear, I think you got your answer.

Unknown said...

Easy to understand.

But I think ViewState["myData"] value get on Page_Load event instead of Page_PreLoad Event.

Powered by Code Imagine