Wednesday, August 25, 2010

Disable a submit button during Post Back

Most of the programmers facing the issue of, how to handle multiple button submits by user at the same time. This article will help you with a small sample. You can restrict multiple button submission by using method ClientScript.GetPostBackEventReference (for more information, please Bing/Google).
#source
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
 <ContentTemplate>
    <asp:Button ID="Button1" Text="Submit" runat="server" onclick="Button1_Click" />
 </ContentTemplate>
</asp:UpdatePanel><br />
<asp:Button ID="Button2" Text="Save (without UpdatePanel)" runat="server" onclick="Button1_Click" />
<br /><br />
<asp:Button ID="Button3" Text="Save (with showing alert)" runat="server" onclick="Button1_Click" />
#code behind
protected void Page_Load(object sender, EventArgs e)
{
  String sString = "this.style.backgroundColor='skyblue'; this.style.color='Red'; this.value='Saving Records... Please Wait...'; this.disabled = true; {0};";
  String sHandler = String.Format(sString, this.ClientScript.GetPostBackEventReference(Button1,  String.Empty));
  Button1.Attributes.Add("onclick", sHandler);
  sHandler = "";
  sHandler = String.Format(sString, this.ClientScript.GetPostBackEventReference(Button2,  String.Empty));
  Button2.Attributes.Add("onclick", sHandler);
  sHandler = "";
  sHandler = String.Format(sString, this.ClientScript.GetPostBackEventReference(Button3, String.Empty));
  Button3.Attributes.Add("onclick", "javascript:alert('hello');" + sHandler);
}
protected void Button1_Click(object sender, EventArgs e)
{
  System.Threading.Thread.Sleep(5000);
}
Note:
Second button will do a full post back. Third button, we can even attach JavaScript validation check before sHandler.
Read more: C# Corner