Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

btnClose is set to CausesValidation = false but not working

Tags:

c#

winforms

I have a close button on my form that I've set to CausesValidation = false. But when I run it and try to close it with ErrorProvider in effect it won't let me close. I've even tried adding to the close routine errorProvider1.Clear() or errorProvider1.Dispose() but still no luck closing the form until I take care of the error.

What I have found to work is in the close if I loop over all the controls and set CausesValidation=false then it works as expected by closing the form despite any errors present.

   private void btnAdd_Click(object sender, EventArgs e)
    {
        if (!this.ValidateChildren()) return;

        DoAddCommand();
    }

    private void DoAddCommand()
    {
        //input
        string input1 = textBox1.Text;
        string input2 = textBox2.Text;
        //process
        this.ValidateChildren();
        decimal sum = Class1.Add(input1, input2);

        //output
        lblSum.Text = sum.ToString();
    }

    private void textBoxNumberEntry_Validating(object sender, System.ComponentModel.CancelEventArgs e)
    {
        TextBox textBox = sender as TextBox;
        decimal number1 = 0;

        try
        {
            number1 = decimal.Parse(textBox.Text);
            errorProvider1.Clear();
        }
        catch (FormatException)
        {
            errorProvider1.SetError(textBox, "Enter a valid number");
            e.Cancel = true;
        }
    }

    private void btnClose_Click(object sender, EventArgs e)
    {
        foreach (Control item in this.Controls)
        {
            item.CausesValidation = false;
        }
        this.Close();
    }
like image 302
Rod Avatar asked Dec 01 '22 19:12

Rod


2 Answers

Try adding those two attributes in your asp:Button tag

CausesValidation="false"

UseSubmitBehavior="false"

The CauseValidation should be enough, but I believe because you have a server side OnCLick event you also need to specify the SubmitBehavior.

Mario

like image 155
Mario Avatar answered Dec 04 '22 09:12

Mario


Most likely what is happening is that one of the TextBoxes have the focus at the time you try to hit the Cancel button, so the validation is already occurring. Your solution works by going through the controls and setting the the CausesValidation property back to False.

A short-cut method is to just turn off the form's AutoValidate property:

private void btnClose_Click(object sender, EventArgs e)
{
  this.AutoValidate = AutoValidate.Disable;
  this.Close();
}
like image 44
LarsTech Avatar answered Dec 04 '22 07:12

LarsTech