balaweblog
balaweblog

Reputation: 15460

page Preinit, Init, load

I am having a doubt in page_init, page preinit, load. I need to know when we use this also where we need to call our objects in different stages of our life cycle.

Please let me know how they will process for each events raised

Upvotes: 3

Views: 13100

Answers (3)

Hrvoje Hudo
Hrvoje Hudo

Reputation: 9024

You will probably find yourself using OnInit and Load. Differences is mostly in viewstate deserialisation event, which happens after OnInit, so you cannot read values from controls in OnInit. Also, in OnInit you can (must) dynamically add new controls to page.
All other things, like filling grids and reading from form fields (textbox, dropdowns,...) goes in Load event.

Upvotes: 1

Chad Braun-Duin
Chad Braun-Duin

Reputation: 2208

Page events happen first before user control events. So the pages PageInit event fires, then the all user controls PageInit events fire. The pages PageLoad event fires, then all user controls PageLoad events fire. etc...

Sometimes developers will put initialization of private objects in their user controls PageLoad handler.

A common gotcha then occurs if the pages PageLoad handler calls a user control method which makes use of uninitialized private objects. Since the user controls PageLoad event hasn't fired yet, those objects are still "null" and an exception is throw (Object not set to instance of Object).

I then typically use the PageInit handler to initialize internal objects within a user control. That way they are not "null" when the public methods that use them are called.

This technique works if you don't call any user control methods from the pages PageInit handler. In my opinion, you shouldn't, though. That is not what handling PageInit in the pages code is for. Use the pages PageLoad handler for user control method calls.

Upvotes: 4

Mark
Mark

Reputation: 14930

Its called the Page lifecycle because at different stages of the page request, different objects are populated with different information.

Here are some good links to read up on:

http://msdn.microsoft.com/en-us/library/ms178472.aspx

http://www.15seconds.com/issue/020102.htm

Upvotes: 4

Related Questions