Sunday, October 21, 2012

Disable button in asp net web page to prevent multiple clicks

When a user clicks a button and the response is slow, there are chances that user may click the button again. The scenario may occur both when the button postbacks synchronously or asynchronously. This type of multiple clicks could be prevented if we could just disable the button just after the first click and enable it again when the processing is done. This is quite easy to implement the task in both the cases: synchronous and asynchronous postbacks.
Before we jump on the topic, you may learn how to click a button on enter key press in an asp.net textbox control. Similarly you may be interested in displaying google search-like watermark in an asp.net textbox control. Both the tutorials help you work with asp.net button control more interactively.

Fig. 1: Just after clicking asp.net button

Fig. 2: After postback occurs

If you are using ajax processing on button click, just disable the button when it is clicked and enable it when the ajax processing is done. If you are using full postback on button click, you may just make the button invisible using client-side-scripting when the click occurs. And you don't need to worry about making it visible since after postback the page will be rendered again, with the button visible as usual. In the snippet below I have shown how to 'disable' (in fact disabling won't work since the server side event is not firing) the asp.net button from client side when it is clicked. 

1. Add reference to jquery file
  1. <span xmlns=""><script src="js/jquery.js" type="text/javascript">  
  2. </script></span>  
  3. <span xmlns=""></span>  
2. Design the web form
  1. <form id="form1" runat="server">  
  2.       
  3.   
  4. <div>  
  5.         <asp:label id="lblMsg" runat="server"></asp:label>  
  6.   
  7.         <asp:button id="Button1" onclick="Button1_Click" runat="server" text="Click Me!">  
  8.         <span id="spanMsg" style="display: none;">Processing..</span>  
  9.     </asp:button></div>  
  10.     </form>  
  11.       
3. Write the client scripting function with jquery
  1.   
4. The code-behind.
  1. protected void Button1_Click(object sender, EventArgs e)  
  2.     {  
  3.         lblMsg.Text +="Current time : "+ DateTime.Now.ToLongTimeString()+"  
  4. ";  
  5.     }  
That's all. When you click the button you catch the client side click event and make the button just invisible. Meantime show 'processing' or similar message. If you love ajax loading image, generate one and show it. From codebehind I have just displayed current time in a label.