Pages

Thursday, August 23, 2012

Explain ASP.Net Page life-cycle events

what is a page life-cycle?

While you requesting a Asp.net page, it goes through a series of processing steps, such as initialization, instantiating controls, restoring and maintaining states, Postback event handling and rendering. Each time you request a page,the page goes through these stages before loading to the Web Browser.

What is page life-cycle events?

Each stages of a page life-cycle will raise events that you could handle to run your code, that would automatically invoke those event methods when certain events are raised. The most important page life-cycle events are ,
  • Page_Init 
  • Page_Load 
  • Control Events 
  • Page_Unload
Events in the page life-cycle (image from http://msdn.microsoft.com)


Page_Init event

Page_Init method, which is the first step in page life-cycle, which automatically called when the page is created. Page_Init event only occurs when first time the page is started. When you PostBack to any page, the Page_Init does not fire. The page and server control fire there Init event when page life-cycle enter the initialization stage. Page_Init event initialize the page's control hierarchy, but you do not try to access the control in this event because it may not be loaded completely .

Page_Load event

Page_Load event guarantees that all controls are fully loaded. The Page_Load event triggers each time when a page load. In Load event, the page's load event is called first. Then, the load event for each child control is called (and their child controls, if any). In Load event, you can access View State information and Web form POST data. Inside the Page Load event, you can check the PostBack and then sets control properties appropriately. To avoid repeat execution of code inside the Page Load event, you can use IsPostBack method.

Control Events (PostBack Events)

In Control Events, Asp.Net calls any events on the page or its controls that caused the PostBack to occur. Control events normally know as PostBack event. TextChanged, SelectedIndexChanged, and similar are examples for Control events. After PostBack call, the Validate method of all validator controls is called.

Page_Unload Event

Page_Unload event is used to do final cleanup process for Controls and Page. For example, closing control specific database connection, closing open files, other user specific task. And destroy any user specific object reference you have created in building the page.

For more information about Post back, please click on What is Post Back in ASP.Net?

No comments:

Post a Comment