What does AutoEventWireUp page property mean?

Solution 1:

When a Page is requested, it raises various events which are considered to be part of it's lifecycle. I keep the visual representation created by Peter Bromberg handy with me.

The AutoEventWireUp property when True, automatically wires up some of these built-in events in the Page life cycle to their handlers. This means that you do not need to explicitly attach these events (using the Handles keyword, for instance, in VB).

Examples of these built-in events would be Page_Init and Page_Load.

If you set AutoEventWireUp to True and provide explicit wiring up of the EventHandlers, you will find them being executed twice! This is one reason why Visual Studio keeps this attribute set to false by default.

Edit: (after Chester89's comment)


It is useful to note that the default value of the AutoEventWireUp attribute of the Page is true, while the default value of the AutoEventWireUp property of the Page class is false

Solution 2:

To add to previous answers; the automatic hooks are applied from TemplateControl.HookUpAutomaticHandlers. This method calls into TemplateControl.GetDelegateInformationWithNoAssert which contains which methods are considered as event handlers.

These are, in System.Web, version 2.0:

  • On all classes deriving from Page: Page_PreInit, Page_PreLoad, Page_LoadComplete, Page_PreRenderComplete, Page_InitComplete, Page_SaveStateComplete.

  • On all classes deriving from TemplateControl: Page_Init, Page_Load, Page_DataBind, Page_PreRender, Page_UnLoad, Page_Error.`

  • Transaction support for all classes deriving from TemplateControl:

    • Page_AbortTransaction, or if it does not exist, OnTransactionAbort
    • Page_CommitTransaction, or if it does not exist, OnTransactionCommit

System.Web, version 4.0, introduced a Page_PreRenderCompleteAsync for all classes derived from Page. That method, if present, will be registered using Page.RegisterAsyncTask and executed automatically "just before the PreRenderComplete event" (source: Page.ExecuteRegisteredAsyncTasks). This method seems very undocumented which suggest that it would be prefered to just call Page.RegisterAsyncTask with your own method instead.

Solution 3:

As mentioned in the article, if you have AutoEventWireUp turned on, asp.net will automatically recognize you have a method with the page_load syntax and call it automatically:

private void Page_Load(object sender, System.EventArgs e)
{
}

This gives you a cleaner code behind at the expense of some (very) small overhead. Notice that if you don't specify it you must explicitly tell asp.net you want to handle the page load event:

this.Load += new System.EventHandler(this.Page_Load);

Note that this applies to other events in the page, as it uses a naming convention as Page_Event.