ASP.Net page life cycle events, orders and purpose

ASP.NET Page Life Cycle order and events Page life cycle is very important concept to understand while working with asp.net, what are the stages we can read the view state values and what is the last event where can write back our view state again. When to load the dynamic controls and when to check the values of dynamically added controls, It is impossible to work without knowing the basics of page life cycle. In this article we will see the different stages and event orders as well as what we can do in different events and why they are necessary.

While developing custom controls, we must be familiar with the page life cycle in order to correctly initialize controls, populate control properties with view-state data, and run control behavior code. The life cycle of a control is based on the page life cycle, and the page raises many of the events that we need to handle in a custom control

Page Life-Cycle Stages:

Before understanding the events and their roles, we will try to understand different stages:

  • Page request: When user types any URL in browser and press hit button, 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.

  • Start: In this stage, page properties such as Request and Response are set, and determines whether the request is a PostBack or a new request of the page and sets the IsPostBack property, UICulture property is also set in this stage.

  • Page initialization: During this stage, each control's UniqueID property is set, any themes are also applied to the page. 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.

  • Load: In this stage, if the current request is a postback, control properties are loaded with information recovered from view state and control state.

  • Validation: During validation, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.

  • Postback event handling: If the request is a postback, any event handlers are called, like the button click etc.
  • Rendering: Before rendering, view state is saved for the page and all controls. During the rendering phase, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream of the page's Response property.
  • Unload: Unload is called 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 andRequest are unloaded and any cleanup is performed.

Life-cycle Events 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.

  • PreInit: Use this event for

    • Check the IsPostBack property to determine whether this is the first time the page is being processed.
    • Create or re-create dynamic controls.
    • Set a master page dynamically.
    • Set the Theme property dynamically.
    • Read or set profile property values.
    • Read view state values, if it is postback.
    • Note: if the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event.
  • Init: Raised after all controls have been initialized and any skin settings have been applied. Use this event to read or initialize control properties.

  • InitComplete: Raised by the Page object. Use this event for processing tasks that require all initialization be complete.

  • PreLoad:

    • Use this event if you need to perform processing on your page or control before the Load event.
    • After the Page raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.
  • 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.
    • Note: 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
  • LoadComplete: Use this event for tasks that require that all other controls on the page be loaded.
  • PreRender: Before this event occurs:

    • The Page object calls EnsureChildControls for each control and for the page.
    • Each data bound control whose DataSourceID property is set calls its DataBind method. For more information, see Data Binding Events for Data-Bound Controls below.
    • The PreRender event occurs for each control on the page. Use the event to make final changes to the contents of the page or its controls.
  • SaveStateComplete: Before this event occurs, ViewState has been saved for the page and for all controls. Any changes to the page or controls at this point will be ignored.

  • 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 that is sent 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. For more information, see Developing Custom ASP.NET Server Controls.
    • A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code.
  • Unload:

    • This event occurs 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.

    • 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.

Event Arguments

Server-based ASP.NET page and control events follow a standard .NET Framework pattern for event-handler methods. All events pass two arguments: an object representing the object that raised the event, and an event object containing any event-specific information. The second argument is usually of type EventArgs, but for some controls is of a type specific to that control. For example, for an ImageButton Web server control, the second argument is of type ImageClickEventArgs, which includes information about the coordinates where the user has clicked.

Postback and Non-Postback Events in Server Controls

In server controls, certain events, typically click events, cause the page to be posted back immediately to the server. Change events in HTML server controls and Web server controls, such as the TextBox control, do not immediately cause a post. Instead, they are raised the next time a post occurs.

Note: If the browser supports it, validation controls can check user input using client script, without a round trip to the server. For details, see Validating User Input in ASP.NET Web Pages. After a page has been posted back, the page's initialization events (PageInit and PageLoad) are raised, and then control events are processed. You should not create application logic that relies on the change events being raised in a specific order unless you have detailed knowledge of page event processing. For details, see ASP.NET Page Life Cycle Overview.

If it useful for your application, you can specify that change events cause the page to post. Web server controls that support a change event include an AutoPostBack property. When this property is true, the control's change event causes the page to post immediately, without waiting for a click event. For example, by default, a CheckBox control's CheckedChanged event does not cause the page to be submitted. However, if you set the control's AutoPostBack property to true, as soon as a user clicks the check box, the page is sent to the server for processing.

Forwarded Events

Web server controls such as the Repeater, DataList, GridView, FormView, and DetailsView controls can contain button controls that themselves raise events. For example, each row in a GridView control can contain one or more buttons created dynamically by templates. Rather than each button raising an event individually, events from the nested controls are forwarded to the container control. The container in turn raises a generic ItemCommand event with parameters that allow you to discover which individual control raised the original event. By responding to this single event, you can avoid having to write individual event handlers for child controls. The ItemCommand event includes the two standard event arguments, an object referencing the source of the event and an event object containing event-specific information.

Binding Page Events

ASP.NET pages raise life-cycle events, by default, you can bind page events to methods using a naming convention of Pageeventname. For example, to create a handler for the page's Load event, you can create a method named PageLoad. At run time, ASP.NET will find methods based on this naming convention and automatically perform the binding between the event and the method. You can use the convention of Page_eventname for any event exposed by the Page class.

Hamden Process manager with a reputed organization, Fond of learning new features and technology related to C#, ASP.Net, SQL Server, MVC etc.I like to help others, if I can
  • asp.net
By Hamden On 24 Jan, 15  Viewed: 3,539

Other blogs you may like

Readonly textbox postback issues and solutions

In many cases we need to use read only text box so user cannot edit the value but readonly textbox will lost its value after postback. Let’s say you have a read only text box to set date by using ajax calendar so after post back date will be lost, other case might be you are setting some value in... By Ali Adravi   On 24 Apr 2013  Viewed: 4,277

Call code behind method from JavaScript in asp.net

There are ways to call a web service method JavaScript, for more detail you can see [how to retrieve data from database using JavaScript in asp.net][1], but is there any way to call a normal method from JavaScript? And the answer is No; show how we can call a code behind method from JavaScript,... By Jonathan King   On 08 Apr 2013  Viewed: 12,486

Gridview paginated data with search and sort functionality in asp.net

Most of the times we need to use GridView control to show tabular data in our asp.net application. We simply write procedure to search the records and bind them with GridView and show 10 to 20 records per page. Have you ever thought that why you are fetching all the records and show only 10 to 20... By Ali Adravi   On 16 Feb 2013  Viewed: 8,518

ASP.Net 4.5 new feature Model Binding

A nice feature with ASP.Net is the model binding, it reduced our code and effort to bind our well know controls like GridView, DataList, Repeater etc. So let’s see how we can bind our old controls in new and easy way. Let’s see how we bind the our grid before 4.5 1. We write the code to get... By Mike .Net   On 17 Jan 2013  Viewed: 3,209

Upload multiple image in multiple size with progress bar in asp.net

In asp.net there is not control to select multiple files and upload them once with progress bar, so we will use a small third party DLL to achieve this functionality. We will use Flajaxian FileUploader, you can download it from [http://www.flajaxian.com][1] We will create three different images... By Hamden   On 12 Jul 2012  Viewed: 6,558