Friday 4 March 2011

How to disable a button when clicked, but still postback (C#/ASP.Net)

If you want to stop a user from clicking a button twice on a web page you can simply disable it when clicked. This can be done by adding the following code to the OnClientClick property of the button...

this.disabled=true;

The problem with this is that it stops the button actually causing a postback event, therefore not triggering any server-side code.

I looked into various methods to solve this niggle, but they all involved client-side script, which I was trying to avoid and therefore avoid the mire that is cross-platform compatibility. I then came across a method of adding client events to controls at the server, and this is working beautifully. I expanded it into a fully working recursive method that you can call from Page_Load to effect this change on all buttons on a page.

Just paste this method into your page...


private void DisableButtonsOnClick(Control control)
{
    if (control is Button)
    {
        (control as Button).Attributes.Add("onclick",
            "this.disabled=true;" +
            Page.ClientScript.GetPostBackEventReference(control, "").ToString());
    }
    else if (control.HasControls())
    {
        foreach (Control child in control.Controls)
        {
            DisableButtonsOnClick(child);
        }
    }
}
Then, simply call
DisableButtonsOnClick(this);
in your Page_Load event.