Thursday, September 29, 2011

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 textbox control. Similarly you may be interested in displaying google search-like watermark in an textbox control. Both the tutorials help you work with button control more interactively.
Fig. 1: Just after clicking 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 button from client side when it is clicked. 
1. Add reference to jquery file

2. Design the web form
3. Write the client scripting function with jquery

4. The code-behind.
protected void Button1_Click(object sender, EventArgs e)
        lblMsg.Text +="Current time : "+ DateTime.Now.ToLongTimeString()+"

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.
Happy Bijaya Dashami (Dashain - the greatest festival of Hindus)!
kick it on


Post a Comment

Hope you liked this post. You can leave your message or you can put your valuable suggestions on this post here. Thanks for the sharing and cooperation!

Popular Posts

Recent Articles