View Light

Disabling a button on click to prohibit multiple clicking

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)
This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available in our efforts to advance understanding of environmental, political, human rights, economic, democracy, scientific, and social justice issues, etc. We believe this constitutes a 'fair use' of any such copyrighted material as provided for in section 107 of the US Copyright Law. In accordance with Title 17 U.S.C. Section 107, the material on this site is distributed without profit to those who have expressed a prior interest in receiving the included information for research and educational purposes. For more information go to: . If you wish to use copyrighted material from this site for purposes of your own that go beyond 'fair use', you must obtain permission from the copyright owner.