Disabling a button on click to prohibit multiple clicking
Posted: 5/27/2005 11:03:13 AM
By: Comfortably Anonymous
Times Read: 2,124
0 Dislikes: 0
Topic: Programming: .NET Framework
If you have a button that triggers a process that that will take a long time and/or could mess things up if double-clicked, this shows an example of how to disable the button on click, then restore it when the process is complete.

This example assumes a System.Web.UI.WebControls.Button named btnButton, with a .Text field of "Do Processing".

Put the following line in the Page_Load section of the page. (Best if in an If Not(IsPostBack) section, but not required.)

btnButton.Attributes.Item("onclick") = _
    "this.disabled=true;this.text='Processing...';" & _
    GetPostBackEventReference(btnButton).ToString & ";"

Note that the GetPostBackEventReference part is very important. This is the part of the code that connects the button click to the code-behind code to handle the button click. Skip this, and your button will go disabled, and the title will change, but the message will never get back to your code that the button has been clicked, and you'll sit there looking stupid. :)

Then, to turn the button back "on" when finished with processing: (If you want to turn the button back on when the processing is finished, if not, skip this code and the button will remain disabled.)

In the btnButton_Click sub, add the following:

btnButton.Text = "Do Processing"
btnButton.Enabled = True
Rating: (You must be logged in to vote)