I had an interview a week ago and one of the questions was what the difference was between OnInit and Onload in ASP.NET? I had no clue and I don't find any simple answers on the net so can someone explain shortly and simple what the difference is between both? (What I found was that the difference was somehting in the lifecycle).
OnInit
(the Init
event) happens after all controls have been initialized, but before ViewState
tracking is enabled. It's called bottom-up (the Init
events for child controls are called before their parent's Init
event).
Init
is a good place to add dynamic controls to your page or user control (though it's not a requirement). If you can, then those controls will have their ViewState
restored automatically during postbacks (see below). It's a risky place to set control properties, though, because they can be overwritten by incoming ViewState
. Init
is the right place to set ViewStateUserKey
, which can help protect your site from one-click attacks. You would also call RegisterRequiresControlState()
from there, if you're using control state.
Right after the Init
event, each control enables ViewState
tracking, so any changes to a control's properties after that will be reflected in ViewState
.
The next events at the page level are InitComplete
and PreLoad
, neither of which is visible at the control level. During a postback, incoming ViewState
is restored into controls between InitComplete
and PreLoad
.
Then comes the Load
event, which happens for both controls and the page. Load
is called first at the parent level, and then for any child controls. A master page behaves like a control on a page with regard to event ordering.
You need to read up on the ASP.NET page lifecycle.
OnInit
happens earlier in the lifecycle - view state changes have not been done yet and tracking of it has not been turned on.
Page_Init
is raised before Page_Load
. Page_Init
is a good place for code that you want executed before you process further such as attaching event handlers to the load event.
it is better not to access controls in this event because you aren't guaranteed they have been created.
The Page_Load is a good place to store code where you initialize values and any controls specific to the page because you know at this point the controls exist and are available.
You will place a lot more code in Page_Load than you will in Page_Init for the majority of your apps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With