Search in Help for developer site.

Thursday 20 October 2016

Difference between ASP.NET Life Cycle and ASP.NET Life Cycle Events with Example

1. Overview

Hello to all my readers, Today i'm going to share difference between ASP.NET Life Cycle and ASP.NET Life Cycle Events.
This question is asked in the most of the interviews and many of the candidates gets confused on this topic.

So After reading this article you will be able to differentiate between ASP.NET Life Cycle and ASP.NET Life Cycle Events.

2. ASP.NET Life Cycle

When an ASP.NET page runs, the page goes through a life cycle in which it performs a series of processing steps. These include initialization, instantiating controls, restoring and maintaining state, running event handler code, and rendering. It is important for you to understand the page life cycle so that you can write code at the appropriate life-cycle stage for the effect you intend.

When When we request to any page/website it goes through some stages that is called ASP.NET Life Cycle.

3. ASP.NET Life Cycle Stages

List of all stage names
  1. Page request
  2. Start
  3. Initialization
  4. Load
  5. Postback event handling
  6. Rendering
  7. Unload
1. Page Request :- 

The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.

2. Start :- 

In the start stage, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. The page also sets the UICulture property.

3. Initialization :- 

During page initialization, controls on the page are available and each control's UniqueID property is set. A master page and themes are also applied to the page if applicable. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.

4. Load :-

During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state. 

5. Postback Event Handling :-

If the request is a postback, control event handlers are called. After that, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page. (There is an exception to this sequence: the handler for the event that caused validation is called after validation.)

6. Rendering :-

Before rendering, view state is saved for the page and all controls. During the rendering stage, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream object of the page's Response property.

7. Unload :-

The Unload event is raised after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and cleanup is performed.

4. ASP.NET Life Cycle Events

Now we will see ASP.NET Life Cycle Events, here it goes.

Within each stage of the life cycle of a page, the page raises events that you can handle to run your own code. For control events, you bind the event handler to the event, either declaratively using attributes such as onclick, or in code.
Pages also support automatic event wire-up, meaning that ASP.NET looks for methods with particular names and automatically runs those methods when certain events are raised. If the AutoEventWireup attribute of the @ Page directive is set to true, page events are automatically bound to methods that use the naming convention of Page_event, such as Page_Load and Page_Init. For more information on automatic event wire-up, see ASP.NET Web Forms Server Control Event Model.
List of all ASP.NET Cycle Events
  1. PreInit
  2. Init
  3. InitComplete
  4. PreLoad
  5. Load
  6. Control events
  7. LoadComplete
  8. PreRender
  9. PreRenderComplete
  10. SaveStateComplete
  11. Render
  12. Unload

1. PreInit :-

Raised after the start stage is complete and before the initialization stage begins.
Use this event for the following:
  • Check the IsPostBack property to determine whether this is the first time the page is being processed. The IsCallback and IsCrossPagePostBack properties have also been set at this time.
  • Create or re-create dynamic controls.
  • Set a master page dynamically.
  • Set the Theme property dynamically.
  • Read or set profile property values.

2. Init :- 


Raised after all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before the Init event of the page.
Use this event to read or initialize control properties.

3. InitComplete :-

Raised at the end of the page's initialization stage. Only one operation takes place between the Init and InitComplete events: tracking of view state changes is turned on. View state tracking enables controls to persist any values that are programmatically added to the ViewState collection. Until view state tracking is turned on, any values added to view state are lost across postbacks. Controls typically turn on view state tracking immediately after they raise their Init event.
Use this event to make changes to view state that you want to make sure are persisted after the next postback.

4. PreLoad :-

Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance.

5. 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.
Use the OnLoad event method to set properties in controls and to establish database connections.

6. Control Events :-

Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.

7. LoadComplete :-

Raised at the end of the event-handling stage.
Use this event for tasks that require that all other controls on the page be loaded.

8. PreRender :-

Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls. (To do this, the Page object calls EnsureChildControls for each control and for the page.)
The Page object raises the PreRender event on the Page object, and then recursively does the same for each child control. The PreRender event of individual controls occurs after the PreRender event of the page.

Use the event to make final changes to the contents of the page or its controls before the rendering stage begins.

9. PreRenderComplete :-

Raised after each data bound control whose DataSourceID property is set calls its DataBind method.

10. SaveStateComplete :-

Raised after view state and control state have been saved for the page and for all controls. Any changes to the page or controls at this point affect rendering, but the changes will not be retrieved on the next postback.

11. Render :-

This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control's markup to send to the browser.
If you create a custom control, you typically override this method to output the control's markup. However, if your custom control incorporates only standard ASP.NET Web server controls and no custom markup, you do not need to override the Render method.
A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code.

12. Unload :-

Raised for each control and then for the page.
In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.

For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks.

Example:-

Lets create an ASP.NET Application to understand it practically. just simply add one webform.aspx, Go to Code Behind file and paste below code snippet.

protected void Page_PreInit(object sender, EventArgs e)
        {
            lblEventName.Text = lblEventName.Text + "<br/>" + "PreInit";
        }

        protected void Page_Init(object sender, EventArgs e)
        {
           
            lblEventName.Text = lblEventName.Text + "<br/>" + "Init";
        }

        protected void Page_InitComplete(object sender, EventArgs e)
        {
           
            lblEventName.Text = lblEventName.Text + "<br/>" + "InitComplete";
        }

        protected override void OnPreLoad(EventArgs e)
        {
            lblEventName.Text = lblEventName.Text + "<br/>" + "PreLoad";
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            lblEventName.Text = lblEventName.Text + "<br/>" + "Load";
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            lblEventName.Text = lblEventName.Text + "<br/>" + "btnSubmit_Click";
        }

        protected void Page_LoadComplete(object sender, EventArgs e)
        {
            lblEventName.Text = lblEventName.Text + "<br/>" + "LoadComplete";
        }

        protected override void OnPreRender(EventArgs e)
        {
            lblEventName.Text = lblEventName.Text + "<br/>" + "PreRender";
        }
        protected override void OnPreRenderComplete(EventArgs e)
        {
            lblEventName.Text = lblEventName.Text + "<br/>" + "PreRenderComplete";
        }

        protected override void OnSaveStateComplete(EventArgs e)
        {
            lblEventName.Text = lblEventName.Text + "<br/>" + "SaveStateComplete";
        }
        protected void Page_UnLoad(object sender, EventArgs e)
        {
            lblEventName.Text = lblEventName.Text + "<br/>" + "UnLoad";
        }

Hit F5 and see the results


5. Summary


I hope guys you liked this article and your confusion about ASP.NET Life Cycle and Event must be cleared. So now onward if any interview ask what is the Difference between ASP.NET Life Cycle and ASP.NET Life Cycle Events then you will be able to answer this question.Like it, Share It.