Skip navigation.

That Pesky Document Schema Picker: Part IIAll recent postsASP.NET and XHTML

Page Events Raised Twice

If you happen to set AutoEventWireup="true" in your @Page directive and wire the same page events in code-behind, you will encounter an interesting side-effect when the wired page events are raised twice.

Suppose, you have the following @Page declaration in your aspx page:

<%@ Page Language="C#" AutoEventWireup="true" … %>

When this page is requested, ASP.NET will attempt to find methods with signatures that look like handlers of page life cycle events. For example, it’ll look for methods with such names as Page_Load, Page_Init, Page_Prerender, etc.

Suppose now you wire page events in code-behind as well:

protected override void OnInit (EventArgs e)
{
  base.OnInit(e);
  this.Page.Load += new EventHandler (Page_Load);
}

In this case the Page_Load method will be called twice! By now the reason should be obvious: the page has automatically wired the Page.Load event to a method it thought was a good match, and you wired the other event handler yourself.

The point of this exercise is to remind to be careful with the AutoEventWireup attribute. Choose your favorite approach and stick to it.

Extra Brownie Points

For the record, the following events are subject to automatic wiring:

  • Page_PreInit
  • Page_Init
  • Page_InitComplete
  • Page_PreLoad
  • Page_Load
  • Page_LoadComplete
  • Page_PreRender
  • Page_PreRenderComplete
  • Page_DataBind
  • Page_SaveStateComplete
  • Page_Unload
  • Page_Error
  • Page_AbortTransaction
  • Page_CommitTransaction
  • OnTransactionAbort
  • OnTransactionCommit

If you want to peek under the hood, navigate to TemplateControl.HookUpAutomaticHandlers in Reflector.

Comments

No comments yet

Emails and Notifications

Would you like to be notified when somebody responds to this post? 

TrackBacks

Sorry, TrackBacks are not allowed.

Submit your comment

Please enter only text since all HTML tags except hyperlinks will be stripped. Hyperlinks will become live links. Any comments with flaming or offensive language will be deleted. Be courteous to other posters. Thank you.

Your name (required):
Your email (optional):
Your site's URL (optional):
Enter this number
Type in the number above:
Comment (required):