AutoEventWireup and Debugging Why Events Are Not Being Hit

If you're new to ASP.net, this may be an issue for you at some point. What if you're programming, you put in your page load function, and then run your code and nothing happens? You turn on debugging and try to step through the code, but it never hits your Page_Load function? What in the world is going on? Why is this happening?

Let's take a look at what happens when you create a new web form page. When you right click in solution explorer, and add a new item, and add a new web form, visual web developer automatically generates an .aspx page for you. At the top you'll find the @ Page directive:

<%@ Page Language="VB" AutoEventWireup="false" 
CodeFile="test.aspx.vb" Inherits="Blog_test" %>
Notice that the property 'AutoEventWireup="false"' is automatically inserted in the @ Page directive. If you assign a Master Page, this isn't an issue in your new page, but it may be an issue in your master page.

Microsoft explains the AutoEventWireup, in that "When AutoEventWireup is true, ASP.NET does not require events to specify event handlers like Page_Load or Page_Init. This means that the Handles keyword in Visual Basic is not required in the server script in the Web Form page. By default, when the ASP.NET Web application is created in Visual Studio, the value of the AutoEventWireup attribute is set to false in the .aspx page or .ascx control, and event handlers are not automatically created. Do not set AutoEventWireup to true if performance is a key consideration."

Since performance should typically always be a consideration, you would want to leave your AutoEventWireup as false, however, what is this "Handles keyword" of which they speak?

This simply means that in your codebehind page, if you desire to have an event handler such as Page_Load or Page_Init, you need to add the Handles keyword like so:

Protected Sub Page_Load(ByVal sender As Object, _
            ByVal e As System.EventArgs) Handles Me.Load

' page load code goes here...

End Sub

What happens if you don't have "Handles Me.Load"? Nothing. Absolutely nothing. You'll run the page, but your Page_Load function will not run. You'll ponder why this code isn't being hit, and you'll even put in debug breakpoints and try to step through it, but it never hits your Page_Load. And until you remember this little tidbit of advice, you'll be pulling out your hair wondering why your code is being ignored.

May your dreams be in ASP.NET!

Nannette Thacker


2 Comments

Comments have been disabled for this content.