OnClick and Handles Caution: Events Firing Twice

By Nannette Thacker

If you're new to ASP.NET, let me offer you a word of caution in regard to using the onclick event within your controls and the Handles key word within your procedure declarations. To demonstrate this, let's create a web form and add these two controls:

<asp:Button ID="Button1" runat="server" Text="Button"/><br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

Double-click the button in your Design view, and you will be taken to the codebehind where you may see that a new Button1_Click Sub has been created for you. Notice the Handles Button1.Click key word has automatically been added to the end of the procedure declaration to handle the Button Click event.

Protected Sub Button1_Click(ByVal sender As Object, _
    ByVal e As System.EventArgs) Handles Button1.Click

End Sub

If you utilize the code as generated, you are safe. However, what if you are copying and pasting from someone else's snippets? You may see onclick="Button1_Click" added to the button:

<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click"/><br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

Beware of this common mistake. You must choose either the onclick within the button or the Handles keyword within the procedure declaration. Let's look at what happens if you have both in your code. To test this, I altered my Label1 to add the value of Label1 and the string " test 1 : " and display it to the screen.

Protected Sub Button1_Click(ByVal sender As Object, _
    ByVal e As System.EventArgs) Handles Button1.Click
        Label1.Text = Label1.Text & " test 1 : "
End Sub

When testing in Internet Explorer 7.0, each time I hit the page, IE would close the browser and ask to send an error report. When I ran the code in FireFox, my label displayed this result:

Label test 1 : test 1 : 

In other words, the code is hit twice, which may not only double your processing, but return unexpected results. So simply be aware of this possibility and avoid using onclick with Handles.

May your dreams be in ASP.net!

Nannette Thacker

19 Comments

Comments have been disabled for this content.