As you know, there are several Page_xxx
event Page_xxx
, such as Init
, Load
, Prerender
... These events exist in controls and pages, as well as in user controls (they are actually a derived form of Control
that contains all these events) .
These events are related to the life cycle of an ASP.NET page.
If you carefully read the page that this link links to, you will understand when events fire. Thus, if you bind an event handler to any page lifecycle event that occurs before the events are triggered, this ensures that the event handlers are bound in time to trigger.
These are the main stages of the life cycle:
PreInit -> Init -> InitComplete -> PreLoad -> Load -> [Control events] -> LoadComplete -> PreRender -> SaveStateComplete -> Render -> Unload
Not all of them have related events, but if necessary, you can override the corresponding OnXxx()
function, for example OnPreInit()
. (This is usually done only for custom server controls).
You can bind events in Page_Init
or Page_Load
because control events are Page_Init
when all controls are loaded . The Load
step occurs from top to bottom, first on the page, and then recursively in all the child controls.
After the Load
completes, the first events that are TextChanged
are change events such as TextChanged
or SelectionChanged
. Then all other events, such as Click
, are triggered.
If you linked events in PreRender or Unload, they will not be triggered. If you did in Init or Load, they would .
So, it may look like it is safe to bind in Init or Load, but this is not true :
It may seem that there is no particular reason to bind them to Init
or Load
, because they will be activated later in the page life cycle. But, since the binding defined in .aspx
occurs during Init
, the programmer expects that all events are already connected in the Load
event. What happens if this programmer raises a child control event in code? The Load
event occurs first in the root of the control tree, and in all child ones - recursively. Thus, by the time the programmer tries to raise the event of the child control, it will no longer be connected. So this will not work as expected. This is more than enough to consider event binding in the Load
event unsafe. Therefore, you should always bind events in Init
.
Take a look at this diagram to see the execution order of page and child events: ASP.NET Page Life Cycle Diagram