ASP.Net ImageButton firing twice

Posted: 12/10/2010

There is a common problem that ASP.NET developers have where their buttons click event fires twice. The most common culprit for this issue comes in the way events are wired up. What happens is, in the ASP.NET tab the developer will specify an OnClick event that tells the page what code to run in the code behind. If there is also a click event setup in the code behind the page could register that same event 2 or 3 times (hence it running two or three times). Let's first look at the 3 types of syntax to wire up a button:

Method #1 – With the handles command on a sub procedure declaration:

    Protected Sub btnValidate_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnValidate.Click
        Call ValidateUser()
    End Sub

Method #2 – Using the "AddHandler" keyword

    AddHandler btnUserLookup.Click, AddressOf btnUserLookup_Click

Method #3 – Using the "OnClick" parameter on the actual ASP.NET tag itself:

    <asp:ImageButton ID="btnValidate" runat="server" ImageAlign="AbsMiddle" OnClick="btnValidate_Click" ImageUrl="~/SharedImages/IconTask.png" />