我的表单上有一个关闭按钮,我设置为CausesValidation = false。但是当我运行它并尝试使用 ErrorProvider 关闭它时,它不会让我关闭。我什至尝试添加到关闭例程中errorProvider1.Clear(),或者errorProvider1.Dispose() but在我处理错误之前关闭表单仍然没有运气。
如果我遍历所有控件并进行设置,CausesValidation=false那么我发现可以正常工作,然后尽管存在任何错误,但通过关闭表单可以按预期工作。
   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();
    }