Let’s say we have a pretty standard form with a textbox and a button (for simplicity). You want to handle a Click event and do some stuff based on user’s input.
I was wondering, does it matter, when exactly you wire up an event handler for the Click event in a code-behind? If it does, where is the best place to put it? Page load? Page init? I’ve tried both places, but didn’t notice any difference. Or it’s just a personal preference of the programmer? I’ve already searched the internet couple of times, but haven’t found any satisfactory answer.
I know when the actual method execute, just not sure about the wiring-up part.
As you know, there are several
Page_xxxevent handlers, likeInit,Load,Prerender… This events exist in Controls, and Pages as well as User controls (in fact they’re derived formControl, which holds all these events).This events are related to the ASP.NET Page Life Cycle
If you read the page pointed to by this link carefully you will understand when the events are triggered. So, if you bind your event handler in any page lifecycle event that happens before the events are triggered, it’s guaranteed that your event handlers will be bound in time to be triggered.
These are the main lifecycle steps:
Not all of them have associated events, but, if it’s necessary you can override the corresponding
OnXxx()function, likeOnPreInit(). (This is usually only done on custom server controls).You can bind events in
Page_InitorPage_Load, because the control events are triggerd after the loading of all the controls has finished. TheLoadstep happens in top-bottom way, first in the Page, and then recursively in all the children controls.After
Loadfinishes, the first events which are triggered are the Change Events, likeTextChangedorSelectionChanged. Then are triggered all the other events, likeClick.If you bound the events in PreRender or Unload, they wouldn’t be triggered. If you did in Init or Load, they would.
So it could look like it’s safe to bind in Init or Load, but that’s not true:
It could look like there’s no special reason to bind them on
InitorLoad, because they’ll be triggered later in the page life cycle. But, as the binding defined in the.aspxhappens duringInit, a programmer will expect that all events are already bound in theLoadevent. What would happen if this programmer raised an event of a child control in code behind? TheLoadevent happens first in the root of the control tree, and them on all of the children, recursively. So, by the time the programmer is trying to raise the event of the child control, it won’t be already bound. So this won’t work as expected. This is more than enough to consider unsafe to bind events inLoadevent. That’s why you should always bind events inInit.Look at this diagram to see the order of execution of Page & children events:
ASP.NET Page Life Cycle Diagram