ASP.NET Page Life Cycle Events Order

There are multiple phases that an ASP.NET page goes through while the web server processes it. Understanding the page life cycle and the governing events are a vital part of development. Developers are likely to know the order of page events but often fail when asked the order of occurrence of a single event in a page with all its child controls.

An ASP.NET page consists of 3 major components: the content page, the master page(s) and the embedded server controls. ( Server controls have the runat=”server” attribute. ) The visual hierarchy is pretty straightforward. A master page can enclose server controls, a content page or a master page. A content page can enclose only server controls.

A simple visual layout of an ASP.NET page.

What developers often misunderstood is that the visual hierarchy of elements differs from the control tree built by the ASP.NET engine. The single most important thing to know about the control tree is that the Page object is the root of the control tree and master pages are all descendants. (Note that all elements – including content and master pages – are derived from System.Web.UI.Control

ASP.NET Page Control Tree Hierarchy The Control Tree of the depicted ASP.NET page. Note that the Master page is a child element.

When dealing with the order of page events MSDN gives a bit vague description. About the Init and Unload events the following can be found. The Init event of individual controls occurs before the Init event of the page. (The unload event is) Raised for each control and then for the page. That is the Init and Unload events are raised in a bottom-up manner. The Init (and Unload) event is raised for child controls first and then for the parent control. As a consequence the Page control is always the last in the order.

In case of Load and PreRender events the order of evaluation is the opposite. Parent control comes first and then child controls follow. This results in having the Page control handling the Load and PreRender events first.

Keeping this in mind can help to avoid a lot of confusion. This is specially true when dealing with master pages.