Overview of ASP.NET Page Life Cycle Events

Overview of ASP.NET Page Life Cycle Events

Overview of ASP.NET Page Life Cycle Events

When an asp.net Page runs, the page perform a series of steps such as Initialization , Instantiating controls, Maintaining & Restoring state, Event Handler, Rendering, that is called page life.   Page life cycle is the sequence of steps which are followed by the all visual studio Compilers. 
At each stage of the page life cycle, the page raises some events, which could be coded. An event handler is basically a function or subroutine, bound to the event, using declarative attributes such as Onclick or handle.

Following are the page life cycle events:
 

  1. PreInit
  2. Init
  3. InitComplete
  4. PreLoad
  5. Load
  6. Control Events
  7. LoadComplete
  8. PreRender
  9. SaveStateComplete
  10. Render
  11. Unload

Here we explain asp.net page life cycle events .

PreInit: Raised after the start stage is complete and before the initialization stage begins. Use this event for the following activities:

  • 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 & Skin property on the page dynamically.
  • Read or set profile property values.

Note : If the request is a postback then the values of the controls have not yet been restored from the view state. If you set a control property at this stage, its value might be overwritten in the next event.

 

Init: Use this event for the following activities:

  1. This event fires after each control has been initialized.
  2. Each control's UniqueID is set and any skin settings have been applied.
  3. Use this event to read or initialize control properties.
  4. The "Init" event is fired first for the bottom-most control in the hierarchy, and then fired up the hierarchy until it is fired for the page itself
  5. We can't get the Text Box value due to view state property is false after click  the  Submit Button.
  6. In this event, we can't able to get the post back values of the controls. 

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. Use this event for the following activities:

  1. Until now the viewstate values are not yet loaded, hence you can use this event to make changes to the view state that you want to ensure are persisted after the next postback.
  2. Raised by the Page object.
  3. Use this event for processing tasks that require all initialization to be complete.

OnPreLoad: Use this event for the following activities

  1. 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.
  2. Before the Page instance raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.
  3. Loads ViewState: ViewState data are loaded to controls.
  4. Loads Postback data: Postback data are now handed to the page controls.
  5. In this event ,Post Back data are also handled by the Page contols
  6. This Event (PreLoad) always Fired after the InitComplete Event.

Load :-The asp.net 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 this event for the following activities:

  1. This is the first place in the page lifecycle that all values are restored.
  2. Most code checks the value of IsPostBack to avoid unnecessarily resetting state.
  3. You may also call Validate and check the value of IsValid in this method.
  4. You can also create dynamic controls in this method.
  5. Use the OnLoad event method to set properties in controls and establish database connections.

Control PostBack Event(s):

Use this event for the following activities:

  1. ASP.NET now calls any events on the page or its controls that caused the PostBack to occur.
  2. Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.
  3. In a postback request, if the page contains validator controls, check the IsValid property of the Page and of individual validation controls before performing any processing.
  4. This is just an example of a control event. Here it is the button click event that caused the postback.

LoadComplete:

Use this event for the following activities:

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

PreRender: Use this event for the following activities:

  1. Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls. PreRender event method is called when page has created all the controls and displayed in browser.
  2. 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.
  3. Use the event to make final changes to the contents of the page or its controls before the rendering stage begins.
  4. This event takes place before saving ViewState, so any changes made here are saved.For example: after this event, you cannot change any property of a button or change any viewstate value.
  5. Each data bound control whose DataSourceID property is set calls its DataBind method.
  6. Use the event to make final changes to the contents of the page or its controls. PreRender method is last place where you can change any things on the page.

 

OnSaveStateComplete: Use this event for the following activities:

  1. Raised after view state and control state have been saved for the page and for all controls.
  2. Any changes to the page or controls at this point will be ignored. Any changes to the page or controls at this point affect rendering, but the changes will not be retrieved on the next postback.
  3. This event is fired after the complete the PreRenderComplete event.
  4. Use this event perform tasks that require the view state to be saved, but that do not make any changes to controls.

Render Method:

  1. This is a method of the page object and its controls (and not an event).
  2. The Render method generates the client-side HTML, Dynamic Hypertext Markup Language (DHTML), and script that are necessary to properly display a control at the browser.

UnLoad

  1. This event is used for cleanup code.
  2. At this point, all processing has occurred and it is safe to dispose of any remaining objects, including the Page object.
  3. Cleanup can be performed on:
    • Instances of classes, in other words objects
    • Closing opened files
    • Closing database connections.
  4. This event occurs for each control and then for the page.
  5. During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream.
  6. If you attempt to call a method such as the Response.Write method then the page will throw an exception.

Note :During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.

 

Asp.net page life cycle events with example

To understand Asp.net page life cycle events order ,we fired all events on a webForm called WebForm1.aspx. Like following

namespace WebApplication1

{

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

    {

        int counter = 0;

        protected override void OnPreInit(EventArgs e)

        {

            //lbl.Text = "";

            counter += 1;

            Response.Write($"{counter}.OnPreInit </br>");

            base.OnPreInit(e);

        }

        protected override void OnInit(EventArgs e)

        {

            lbl.Text = "";

            counter += 1;

            Response.Write($"{counter}.OnInit </br>");

            base.OnInit(e);

        }

        protected override void OnInitComplete(EventArgs e)

        {

            counter += 1;

            Response.Write($"{counter}.OnInitComplete </br>");

            base.OnInitComplete(e);

        }

        protected override void OnPreLoad(EventArgs e)

        {

            counter += 1;

            Response.Write($"{counter}.OnPreLoad </br>");

            base.OnPreLoad(e);

        }

        protected override void OnLoad(EventArgs e)

        {

            counter += 1;

            Response.Write($"{counter}.OnLoad </br>");

            base.OnLoad(e);

        }

        protected override void OnLoadComplete(EventArgs e)

        {

            counter += 1;

            Response.Write($"{counter}.OnLoadComplete </br>");

            base.OnLoadComplete(e);

        }

        protected override void OnPreRender(EventArgs e)

        {

            counter += 1;

            Response.Write($"{counter}.OnPreRender </br>");

            base.OnPreRender(e);

        }

        protected override void OnSaveStateComplete(EventArgs e)

        {

            counter += 1;

            Response.Write($"{counter}.OnSaveStateComplete </br>");

            base.OnSaveStateComplete(e);

        }

        protected override void OnPreRenderComplete(EventArgs e)

        {

            counter += 1;

            Response.Write($"{counter}.OnPreRenderComplete </br>");

            base.OnPreRenderComplete(e);

        }

        protected override void OnUnload(EventArgs e)

        {

            counter += 1;

          //  Response.Write($"{counter}.OnPreInit </br>");

            base.OnUnload(e);

        }

        protected void Page_Load(object sender, EventArgs e)

        {

            lbl.Text = "";

 

        }

       

        protected void load_Click(object sender, EventArgs e)

        {

            counter += 1;

            Response.Write($"{counter}.ButtonClick </br>");

        }

    }

}

Explanation:

Here I add a label control named it lbl. Which is not available in OnPreInit event. Available from Init event.To read sequence of all events I create a counter variable in codebehiened and increment when an event fired.

Display the counter value with eventName using Response.Write()method.            Such as : Response.Write($"{counter}.ButtonClick </br>");

Here $ is interpolation which concate all string in its scope, </br> used for line break .

Run the application  & you will see following output.

 

 

 

We found all event fired except control event. When we click on button Control event will fired and placed after Load event. To examine this click on button & get following output:

 

 

 

 

That’s all thank you.

 

 

 

Back to Blogs