Tuesday, 17 April 2012

Difference between page_init, page_load and page_prerender events

page_init

This event is the first event to occur when an ASP.NET page is executed. This is the event where you should be performing any initialization steps that you need to setup or create instances of server controls.

A page's controls (and the page itself) are first initialized in their raw form. By declaring your objects within the constructor of your C# code-behind file, the page knows what types of objects and how many to create. Once you have declared your objects within your constructor, you may then access them from any sub class, method, event, or property. However, if any of your objects are controls specified within your ASPX file, at this point the controls have no attributes or properties. It is dangerous to access them through code, as there is no guarantee of what order the control instances will be created (if they are created at all). The initialization event can be overridden using the OnInit method.

Caution:

1. It is generally advised not to access controls in this event as there is no guarantee of the controls been created at this stage.
2. This event fires only the first time the page is loaded and from the next time on a postback page_init is not fired.

page_load

This is the event where most of our work will be done. This event occurs when all objects/controls on the page are created and will be available for use.

Caution:

1. This event is called eveytime when the post back occurs. So, the code in this event is executed again and again. If you want some code to be executed only first page load, use the isPostBack method.

page_prerender

It is the brief moment before the page is displayed to the user as HTML. PreRender event occurs for each control on the page. You can use this event to make final changes to the contents of the page or its controls. Unlike page_init, this event is loaded every time when the page is posted back.

The point at which the objects are prerendered is the last time changes to the objects can be saved or persisted to viewstate. This makes the PreRender step a good place to make final modifications, such as changing properties of controls or changing Control Tree structure, without having to worry about ASP.NET making changes to objects based off of database calls or viewstate updates. After the PreRender phase those changes to objects are locked in and can no longer be saved to the page viewstate. The PreRender step can be overridden using OnPreRender

No comments:

Post a Comment