Disabling Buttons on your form once it Clicked

By | August 6, 2010

I just want to share this code snippet which I used a lot on my web forms.
Its a simple code for preventing those double clicks of users when they already hit the submit button, its anoying sometimes when the internet is slow and saving something takes a lot of time which makes the user wonder did I click it already or not?  So they click it again and if you dont have a fancy validation on your code behind then it ends up you have multiple values on your database with the same data.  One solution to this is to show progress bar that its saving but still it does not prevent the users to click the button again so what you can do is just to disable the button once the user clicks it and the best way to do that is on the client side as if its on the server side it defeats the purpose as it will do server round trips and have the same issue all over again.

To do that I had added a piece of code on my code behind in Page Load event of the page to add an onclick attribute to my button that disables it once users click on it.  Now why do I do that on the Code behing and not directly adding it on the aspx? The answer is because you cant as you already have an onclick event which handles the method you want to invoke.

Look at the example below, with my btnSave button I already have an onclick event which calls btnSave_Click

<asp:Button ID="btnSave" runat="server" CssClass="NormalTextLarge" onclick="btnSave_Click" Text="Submit" />

So here is how I do it on the Page Load event

System.Text.StringBuilder oStrBldr = new System.Text.StringBuilder();
oStrBldr.Append("if (typeof(Page_ClientValidate) == 'function') { ");
oStrBldr.Append("if (Page_ClientValidate() == false) { return false; }} ");
oStrBldr.Append("this.value = 'Please wait...';");
oStrBldr.Append("this.disabled = true;");

oStrBldr.Append(ClientScript.GetPostBackEventReference(this.btnSave, ""));
oStrBldr.Append(";");

this.btnSave.Attributes.Add("onclick", oStrBldr.ToString());
Recommended

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.