btnClose设置为CausesValidation = false但不起作用

Rod*_*Rod 3 c# winforms

我在我的表单上有一个关闭按钮,我已经设置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();
    }
Run Code Online (Sandbox Code Playgroud)

Mar*_*rio 6

尝试在asp:Button标记中添加这两个属性

CausesValidation ="false"UseSubmitBehavior ="false"

CauseValidation应该足够了,但我相信因为你有一个服务器端OnCLick事件,你还需要指定SubmitBehavior.

马里奥

  • -1问题是关于Windows窗体,而不是ASP.NET. (3认同)
  • 尽管最初的问题是关于Windows窗体的,但我发现此解决方案对于ASP.NET中的类似情况很有帮助。 (3认同)