C# – Difference OnInit and OnLoad in ASP.NET


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).

Best Solution

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.