Ketone Cops

July 7, 2008

Button event firing twice in ASP.NET

Filed under: ASP.NET 2.0,programming — delroger @ 12:42 pm

I’d got a File Upload control on one of my webpages which was causing a strange problem: when a user clicked the button to upload a file, the button’s click event was firing twice, so the file uploaded twice and a database insert query happened twice.

I’d initially thought that the Page_Load event was occurring twice, since this is quite well documented if, for instance, you have <img src=”#”>.  Debugging the code demonstrated that this was not happening; the Page_Load only fired once, while the btnUpload_Click fired twice.

The problem turned out to be that the code for my button was as follows:

<asp:Button ID=”btnUpload” runat=”server” OnClick=”btnUpload_Click” Text=”Upload File” />

 There are essentially two events for the button: both runat=”server” and OnClick fire the same event, hence everything happening twice.  The solution is simply to remove the OnClick command. 

But why was this happening in the first place? I think it is because I originally had an AJAX UpdatePanel on the page and the control had been part of that initially: the OnClick was created when the File Upload control was dragged into the UpdatePanel; after removing the UpdatePanel, the OnClick still remained.

Advertisements

6 Comments »

  1. Very Thank you !!!

    Comment by مهرگان طراحي وب نرم افزار آموزش — September 5, 2008 @ 11:49 am

  2. Hi,

    Lots of Thanks.

    Comment by Vishal Jani — October 28, 2009 @ 5:21 am

  3. THANKS!!!! i spent an hour on this before seeing your post. DUHHH!!!

    Comment by john — March 14, 2011 @ 9:10 pm

  4. Thanks.. you really help me

    😉

    Comment by Othman — July 3, 2011 @ 5:52 am

  5. Thanks a Lot It worked 🙂

    Comment by Bhavini — December 29, 2011 @ 7:56 am

  6. Thanks a lot!

    Comment by bharats — March 26, 2012 @ 6:42 am


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: