Popular Posts

Friday, 13 September 2013

TWO SIMPLE STEPS FOR DISABLING THE BUTTON ON SUBMIT

TWO SIMPLE STEPS FOR Disabling THE BUTTON ON SUBMIT


It is always required for the application to disable the submit /button button until the request sent has been responded. So that the user cannot again and again starts  clicking on the button and causing error in application. This can be done in many ways i.e. using jquery,javascript,third party tools etc....but there are two very simple ways to do it...LETS SEE HOW CAN WE..................SO LET’S LEARN...............


WAY 1.
AT the time of submit button we will add/call the function that will disable the button until the response came .it can be done like this:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

        }
        this.Submit1.Attributes.Add("onclick", DisableTheButton(this.Page, this.Submit1));
       
    }
i.e on page_load methos call the submit button “on-click” event and here we cal the disable the button method on the SUBMIT1 button (SUBMIT1 is the button id)

THE METHOD:
private string DisableTheButton(Control pge, Control btn)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append("if (typeof(Page_ClientValidate) == 'function') {");
        sb.Append("if (Page_ClientValidate() == false) { return false; }} ");
        sb.Append("if (confirm('Are you sure to proceed?') == false) { return false; } ");
        sb.Append("this.value = 'Please wait Getting Result...';");
        sb.Append("this.disabled = true;");
        sb.Append(pge.Page.GetPostBackEventReference(btn));
        sb.Append(";");
        return sb.ToString();
    }

Here in the methos we have also added an CONFIRM DIALOG BOX for the conformation of the button press/submit.it will execute futher only on clicking yes on conform box.
Also we add a message that display on the button ......here we display
'Please wait Getting Result...'
So all the needed functionality are covered.
This is simple and easy way without using any jquery or javascripts etc.


WAY2:
If simply you want to disable the button this can be done very easyly using try catch blocks....SHOCKING!!!!!


This is the cheapest method that can be followed but is not used by any developer .
PLEASE DONT LAUGH ON YOUR SENSES AFTER DISCOVERING THE METHOD!!!!

CODE:
On button click event just disable the button you clicked and on finally bolck just enable it.
  protected void Button1_Click(object sender, EventArgs e)
    {
       
        try
        {
Button1.Enabled=True;
//your rest of the code here
           
        }
        catch (Exception ex)
        {
            Console.WriteLine("{0} Exception caught.", ex);
        }

        finally
        {
       
        Button1.Enabled=False;

        }
    }





No comments :

Post a Comment