When an ASP. NET page runs, this page goes through a life cycle, and a series of processing steps are performed during the life cycle. These steps include initializing, instantiating the control, restoring and maintaining the state, running the event handler code, and rendering. Understanding the page life cycle is important because doing so allows you to write code at the appropriate stage of the life cycle to achieve the desired results. In addition, if you are developing a custom control, you must familiarize yourself with the page life cycle to properly initialize the controls, populate the control properties with view-state data, and run any control behavior code. (The life cycle of a control is based on the life cycle of the page, but the page raises more control events than are available in a separate ASP. )
General page life cycle stageIn general, pages go through each of the stages outlined in the following table. In addition to the page life cycle phase, there is an application phase before and after the request, but these stages are not specific to the page.
Stage |
Description |
Page request |
Page requests occur before the page life cycle begins. When a user requests a page, ASP. NET determines whether the page needs to be parsed and compiled (thereby starting the life cycle of the page), or whether the cached version of the page can be sent in response without running the page. |
Begin |
In the start phase, page properties, such as Request and Response, are set. At this stage, the page also determines whether the request is a postback request or a new request, and sets the IsPostBack property. Also, during the start phase, the UICulture property of the page is set. |
Page initialization |
During page initialization, the controls in the page can be used, and the UniqueID property of each control is set. In addition, any theme will be applied to the page. If the current request is a postback request, the postback data has not yet been loaded, and the control property value has not been restored to the value in view state. |
Load |
During load, if the current request is a postback request, the control property will be loaded with information recovered from view state and control state. |
Verify |
During validation, the Validate method for all validator controls is invoked, and this method sets the IsValid properties for each validator control and page. |
Postback event handling |
If the request is a postback request, all event handlers are called. |
Present |
View state is saved for the page and all controls before rendering. During the rendering phase, the page calls the Render method for each control, and it provides a text writer to write the output of the control to the outputstream of the Response property of the page. |
Unloading |
The unload is called when the page is fully rendered and the page has been sent to the client, and the page is ready to be discarded. At this point, the page properties (such as response and Request) are unloaded and cleanup is performed. |
Life Cycle Events
In each stage of the page life cycle, the page raises events that can run your own code for processing. For control events, you can bind an event handler to an event by declaratively using properties such as onclick, or by using code.
The page also supports automatic event connections, that is, ASP. NET will look for methods that have a specific name and automatically run them when a specific event is raised. If the AutoEventWireup property of the @ Page directive is set to true (or if the property is not defined because the property defaults to True), the page event is automatically bound to a method that uses the naming convention of the Page_ event, such as Page_Load and Page_Init).
The following table lists the most commonly used page life cycle events. In addition to the events listed, there are other events, but most page processing scenarios do not use these events. Instead, they are primarily used by server controls on ASP. NET pages to initialize and render themselves. If you are writing your own ASP. NET server controls, you need to learn more about these phases.
Page Events |
Typical use |
PreInit |
Use this event to perform the following actions:
Check the IsPostBack property to determine whether the page is being processed for the first time.
Creates or re-creates a dynamic control.
Dynamically set the master page.
Dynamically sets the Theme property.
Reads or sets the profile property value.
Description |
If the request is a postback request, the value of the control has not been restored from view state. If a control property is set at this stage, its value may be overwritten in the next event. |
|
Init |
Raised after all controls have been initialized and all skin settings have been applied. Use this event to read or initialize the properties of a control. |
InitComplete |
Raised by the Page object. Use this event to handle tasks that require that all initialization work be completed first. |
Preload |
Use this event if you need to perform processing on a page or control before the Load event. After the Page raises the event, it loads the view state for itself and all the controls, and then processes any postback data that is included in the request instance. |
Load |
The page increases the OnLoad event method on page and then recursively performs the same action on each child control, so that it repeats until the page and all controls are loaded. Use the OnLoad event method to set the properties in the control and establish a database connection. |
Control events |
Use these events to handle specific control events, such as the Button control's Click event or the TextChanged event of a TextBox control.
Description |
In a postback request, if the page contains a validator control, check the IsValid property of the page and individual validation controls before performing any processing. |
|
LoadComplete |
Use this event for a task that needs to load all other controls on the page. |
PreRender |
Before the event occurs:
The Page object calls EnsureChildControls for each control and page.
Each data-bound control that has the DataSourceID property set will call the DataBind method. For more information, see Data-binding events for data-bound controls later in this topic.
The PreRender event occurs for each control on the page. Use this event to make a final change to the contents of a page or its controls. |
Savestatecomplete |
ViewState has been saved for the page and all controls before the event occurred. Any changes made to the page or control at this time will be ignored. Use this event to perform tasks that require that view state be saved, but that no changes are made to the control. |
Render |
This is not an event; At this stage of processing, the Page object will be called on each control with this method. All ASP. NET Web server controls have a Render method that is used to write the control tokens that are sent to the browser. If you create a custom control, you typically override this method to output the markup for the control. However, if your custom control merges only standard ASP. NET Web server controls and does not merge custom tags, you do not need to overwrite the Render method. The user control (. ascx file) automatically merges the rendering, so you do not need to explicitly render the control in your code. |
Unload |
The event occurs first for each control, and then for that page. In a control, use this event to perform a final cleanup of a specific control, such as closing a control-specific database connection. For the page itself, use this event to perform the final cleanup work, such as closing open files and database connections, or completing logging or other requests for specific tasks.
Description |
During the unload phase, the page and its controls are rendered so that no further changes can be made to the response stream. If you try to invoke a method, such as the Response.Write method, the page throws an exception. |
|
additional page life-cycle Considerations
Each ASP. NET server control has its own life cycle, which is similar to the page life cycle. For example, the Init and Load events for a control occur during the corresponding page event.
Although both Init and Load occur recursively on each control, they occur in the opposite order. The Init event (and also the Unload event) for each child control occurs before the corresponding event is raised for its container (from bottom to top). However, the container's Load event occurs before the load event of its child controls (top to bottom).
You can customize the appearance or content of a control by handling events for the control, such as the Click event of the Button control and the SelectedIndexChanged event for the ListBox control. In some cases, you may also want to handle the DataBinding or databound events of the control.
When inheriting a class from the page class, you can override the methods in the base class of the page in addition to the events raised by the page. For example, you can override the InitializeCulture method of a page to dynamically set culture information. Note that when you use the Page_ event syntax to create an event handler, the base implementation is called implicitly, so you do not need to call it in the method. For example, the OnLoad method of the page base class is always called regardless of whether the Page_Load method is created. However, if you overwrite the page's OnLoad method with the Override keyword (Overrides in Visual Basic ), you must explicitly call the base method. For example, if you overwrite the OnLoad method in a page, you must call base. Load (MyBase.Load in Visual Basic ) to run the base implementation.
Catch-up events for added controls
If controls are created dynamically at run time, or are created declaratively in a template of a data-bound control, their events are not initially synchronized with the events of other controls on the page. For example, for controls that are added at run time, the Init and Load events may occur much later in the page life cycle than the same events for controls created declaratively. Thus, from the moment of instantiation, the event of a dynamically added control has been occurring after the event of the control in the template until it catches the event that the control has joined the Controls collection.
In general, you do not have to worry about this situation unless you have nested data-bound controls. If a child control has performed data binding, but its container control has not yet performed data binding, the data in the child control may not be synchronized with the data in its container control. This is especially true if the data in the child controls is handled according to the data-bound values in the container control.
For example, suppose you have a GridView, and each row of it displays a company record, and in addition, there is a ListBox control that contains a list of company managers. To populate the list of managers, you need to bind the ListBox control to a data source control (such as SqlDataSource), which uses CompanyID in the query to retrieve company manager data.
If you set the data-binding properties of a ListBox control declaratively (such as DataSourceID and DataMember), the ListBox control attempts to bind to its data source during the DataBinding event that contains the row. However, the CompanyID field of the row does not contain a value until the RowDataBound event of the GridView control occurs. In this case, the child controls (the ListBox control) are bound first, and then the binding contains the controls (the GridView control), so their data-binding phase is not synchronized.
To avoid this situation, you need to place the data source control of the ListBox control in the same template item as the ListBox control itself, and do not set the data-binding properties of the ListBox declaratively. Instead, they should be set programmatically at run time during the RowDataBound event, so that the ListBox control is bound to its data when CompanyID information is available.
Data-bound events for data-bound controls
To help you understand the relationship between the page life cycle and data-bound events, the following table lists data-related events in data-bound controls such as the GridView, DetailsView, and FormView controls.
Control events |
Typical use |
DataBinding |
This event is raised by a data-bound control before the PreRender event that contains the control (or Page object), which marks the starting point of the binding process for the control to the data. Use this event to open the database connection manually, if necessary. (data source controls typically do not need to do this.) ) |
RowCreated (GridView only) or itemcreated (DataList, DetailsView, SiteMapPath, DataGrid, FormView, Repeater, and ListView controls) |
Use this event to manipulate content that is not dependent on data binding. For example, at run time, you can programmatically add formatting to a header or footer row in a GridView control. |
|
RowDataBound (GridView only) or ItemDataBound (DataList, SiteMapPath, DataGrid, Repeater, and ListView controls) |
When the event occurs, the data in the row or item is available, so you can format the data or set the FilterExpression property on the child data source control to display the related data in the row or item. |
DataBound |
The event marks the end of a data-binding operation in a data-bound control. In the GridView control, data binding is done for all rows and any child controls. Use this event to format data-bound content, or to start data binding in other controls that rely on values from the contents of the current control. (For more information, see "Catching events for added controls" earlier in this topic.) ) |
Login Control Events
The Login control can use the settings in the Web. config file to automatically manage membership validation. However, if your application requires you to customize how the control works, or if you want to understand how the Login control event relates to the page life cycle, you can use the events listed in the following table.
Control events |
Typical use |
Loggingin |
This event is raised when a page's LoadComplete event occurs during a postback. It marks the start of the logon process. Use this event for tasks that must occur before the validation process begins. |
Authenticate |
This event is raised after the Loggingin event. Use this event to override or enhance the default validation behavior of the Login control. |
|
LoggedIn |
This event is raised after validating the user name and password. Use this event to redirect the text in a control to another page or to a dynamic setting. If an error occurs or the validation fails, the event does not occur. |
LoginError |
If the validation fails, the event is raised. Use this event to set the problem in the control to interpret the text or to direct the user to a different page. |