Home
Manage Your Code
Snippet: Double Click Prevention For ASP.NET (C#)
Title: Double Click Prevention For ASP.NET Language: C#
Description: By putting this in a base page, you can pass it a control and this will ensure that the control (such as a button) will not be clicked twice. This is nice when you want to prevent the page from being submitted twice. Views: 1212
Author: Joel Ross Date Added: 7/13/2005
Copy Code  
1public void SetDoubleClickPrevention(System.Web.UI.WebControls.WebControl control){
2
3	if(!this.IsClientScriptBlockRegistered(control.ClientID + "DoubleClickPrevention")){
4		System.Text.StringBuilder sb = new System.Text.StringBuilder();
5		sb.Append("<script>\n\r");
6		sb.Append("var " + control.ClientID + "Clicked = false;");
7		sb.Append("function " + control.ClientID + "click(){\n\r");
8		sb.Append("	if(typeof(Page_ClientValidate) == 'function'){\n\r");
9		sb.Append("		if(Page_ClientValidate()) {\n\r");
10		sb.Append("			if(" + control.ClientID + "Clicked){\n\r");
11		sb.Append("				return false;\n\r");
12		sb.Append("			} else {\n\r");
13		sb.Append("				" + control.ClientID + "Clicked = true;\n\r");
14		sb.Append("				return true;\n\r");
15		sb.Append("			} ");
16		sb.Append("		} ");
17		sb.Append("	} else { ");
18		sb.Append("		if(" + control.ClientID + "Clicked){\n\r");
19		sb.Append("			return false;\n\r");
20		sb.Append("		} else {\n\r");
21		sb.Append("			" + control.ClientID + "Clicked = true;\n\r");
22		sb.Append("			return true;\n\r");
23		sb.Append("		} ");
24		sb.Append("	} ");
25		sb.Append("} ");
26		sb.Append("</script>\n\r");
27		this.RegisterClientScriptBlock(control.ClientID + "DoubleClickPrevention", sb.ToString());
28
29		control.Attributes.Add("onclick", "return " + control.ClientID + "click();");
30	}
31}
32