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).
C# – Difference OnInit and OnLoad in ASP.NET
asp.netc
Best Answer
OnInit
(theInit
event) happens after all controls have been initialized, but beforeViewState
tracking is enabled. It's called bottom-up (theInit
events for child controls are called before their parent'sInit
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 theirViewState
restored automatically during postbacks (see below). It's a risky place to set control properties, though, because they can be overwritten by incomingViewState
.Init
is the right place to setViewStateUserKey
, which can help protect your site from one-click attacks. You would also callRegisterRequiresControlState()
from there, if you're using control state.Right after the
Init
event, each control enablesViewState
tracking, so any changes to a control's properties after that will be reflected inViewState
.The next events at the page level are
InitComplete
andPreLoad
, neither of which is visible at the control level. During a postback, incomingViewState
is restored into controls betweenInitComplete
andPreLoad
.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.