ASP.Net ImageButton firing twice


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" />

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.