How to prevent multiple button clicks?

  • Thread starter Thread starter Christian Schwarz
  • Start date Start date
C

Christian Schwarz

Hello,

what is the recommended way to prevent a user from double clicking a button.
Disabling the button within the Click-Event handler does not seem to solve
the problem.

Greetings, Christian
 
Christian said:
Hello,

what is the recommended way to prevent a user from double clicking a button.
Disabling the button within the Click-Event handler does not seem to solve
the problem.

Greetings, Christian

I'm assuming your button click procedure takes a while and you don't
want it starting twice. Try this...

in VB -- static boolean

private sub button_click()
static ButtonClicked as boolean = false
if ButtonClicked then
exit sub
end if
try
ButtonClicked = True
... do stuff ...
finally
ButtonClicked = False
end try
end sub

-- timer based - 1000 ticks = roughly 1 second

dim LastClickTick as integer
private sub button_click()
try
if System.Environment.TickCount - LastClickTick < 1000 then
exit sub
else
... do stuff ...
end if
finally
LastClickTick = System.Environment.TickCount
end try
end sub
 
Instead of the VB-specific static keyword use a class/form level boolean; it
is cleaner and more efficient (static in VB is there for backwards
compatibility, if you look at the IL it is ugly).

You could also remove the event handler at the first line of the button
click and re-add it at the last line. Similar to what I show here (solves a
different problem but the principle is the same):
http://www.danielmoth.com/Blog/2005/03/back-to-basics-1.html

Cheers
Daniel
 
Daniel said:
Instead of the VB-specific static keyword use a class/form level
boolean; it is cleaner and more efficient (static in VB is there for
backwards compatibility, if you look at the IL it is ugly).

You could also remove the event handler at the first line of the button
click and re-add it at the last line. Similar to what I show here
(solves a different problem but the principle is the same):
http://www.danielmoth.com/Blog/2005/03/back-to-basics-1.html

Nice replay as always.

I believe you have a typo though, should this second not be there?

2) The alternative is not to declare a boolean, **not** to change the
selectedindexchanged event handler and simply change the button click
method body like this:
 
My REPLY had a typo too. :o)

Russ said:
Nice replay as always.

I believe you have a typo though, should this second not be there?

2) The alternative is not to declare a boolean, **not** to change the
selectedindexchanged event handler and simply change the button click
method body like this:
 
I don't think I have a typo. The "not" should be there. You do not have to
change the selectedindexchanged event handler. I.e. you do not have to
change the body of the method.

If you meant something else let me know... if not, thanks for the feedback.

Cheers
Daniel
 
Back
Top