单击表单的取消按钮后如何跳过验证

发布于 2024-08-14 01:31:39 字数 260 浏览 10 评论 0原文

我使用 C#。 我有一个带有编辑框和取消按钮的 Windows 窗体。编辑框包含验证事件中的代码。每次编辑框失去焦点时都会执行该代码。当我单击“取消”按钮时,我只想关闭表单。我不希望对编辑框执行任何验证。如何才能做到这一点?

这里有一个重要的细节:如果验证失败,则

            e.Cancel = true;

阻止离开控件。

但是,当用户单击“取消”按钮时,无论如何都应该关闭表单。如何实施?

I use C#.
I have a Windows Form with an edit box and a Cancel button. The edit box has code in validating event. The code is executed every time the edit box loses focus. When I click on the Cancel button I just want to close the form. I don't want any validation for the edit box to be executed. How can this be accomplished?

Here is an important detail: if the validation fails, then

            e.Cancel = true;

prevents from leaving the control.

But when a user clicks Cancel button, then the form should be closed no matter what. how can this be implemented?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

痞味浪人 2024-08-21 01:31:40

在编辑框的验证代码上方添加:

if (btnCancel.focused)
  {
     return;
  }

这样就可以了。

Just above the validation code on the edit box add:

if (btnCancel.focused)
  {
     return;
  }

That should do it.

云雾 2024-08-21 01:31:40

作为 Daniel Schaffer 答案的补充:如果在编辑框失去焦点时进行验证,您可以 禁止按钮激活以绕过本地验证并无论如何退出。

public class UnselectableButton : Button
{
    public UnselectableButton()
    {
        this.SetStyle(ControlStyles.Selectable, false);
    }
}

或者如果您使用 DevExpress:

this.simpleButtonCancel.AllowFocus = false;

请注意,这样做会改变键盘体验:选项卡将不再集中在取消按钮上。

In complement of the answer of Daniel Schaffer: if the validation occurs when the edit box loses focus, you can forbid the button to activate to bypass local validation and exit anyway.

public class UnselectableButton : Button
{
    public UnselectableButton()
    {
        this.SetStyle(ControlStyles.Selectable, false);
    }
}

or if you use DevExpress:

this.simpleButtonCancel.AllowFocus = false;

Note that doing so will change the keyboard experience: the tab will focus anymore on the cancel button.

带刺的爱情 2024-08-21 01:31:40

也许您想使用BackgroundWorker 给予一点延迟,以便您可以决定是否应该运行验证。这是避免表单关闭时验证的示例。

    // The flag
    private bool _isClosing = false;

    // Action that avoids validation
    protected override void OnClosing(CancelEventArgs e) {
        _isClosing = true;
        base.OnClosing(e);
    }

    // Validated event handler
    private void txtControlToValidate_Validated(object sender, EventArgs e) {           
        _isClosing = false;
        var worker = new BackgroundWorker();
        worker.DoWork += worker_DoWork;
        worker.RunWorkerAsync();
        worker.RunWorkerCompleted += worker_RunWorkerCompleted;
    }

    // Do validation on complete so you'll remain on same thread
    void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
        if (!_isClosing)
            DoValidationHere();
    }

    // Give a delay, I'm not sure this is necessary cause I tried to remove the Thread.Sleep and it was still working fine. 
    void worker_DoWork(object sender, DoWorkEventArgs e) {
        Thread.Sleep(100);
    }

Maybe you want to use BackgroundWorker to give little bit delay, so you can decide whether validation should run or not. Here's the example of avoiding validation on form closing.

    // The flag
    private bool _isClosing = false;

    // Action that avoids validation
    protected override void OnClosing(CancelEventArgs e) {
        _isClosing = true;
        base.OnClosing(e);
    }

    // Validated event handler
    private void txtControlToValidate_Validated(object sender, EventArgs e) {           
        _isClosing = false;
        var worker = new BackgroundWorker();
        worker.DoWork += worker_DoWork;
        worker.RunWorkerAsync();
        worker.RunWorkerCompleted += worker_RunWorkerCompleted;
    }

    // Do validation on complete so you'll remain on same thread
    void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
        if (!_isClosing)
            DoValidationHere();
    }

    // Give a delay, I'm not sure this is necessary cause I tried to remove the Thread.Sleep and it was still working fine. 
    void worker_DoWork(object sender, DoWorkEventArgs e) {
        Thread.Sleep(100);
    }
扶醉桌前 2024-08-21 01:31:40

这是一个老问题,但我最近遇到了这个问题并通过以下方式解决了它:

第一,我们将 UserControl 加载到“shell”Form 中,该外壳具有保存和取消按钮。 UserControl继承了一个接口(如IEditView),具有保存取消验证<的功能。 /strong> 和 ToggleValidate

在 shell 表单中,我们使用鼠标进入和鼠标离开,如下所示:

    private void utbCancel_MouseEnter(object sender, EventArgs e)
    {
        ((Interface.IEdit)tlpMain.Controls[1]).ToggleValidate();
    }

    private void utbCancel_MouseLeave(object sender, EventArgs e)
    {
        ((Interface.IEdit)tlpMain.Controls[1]).ToggleValidate();
    }

然后在 ToggleValidate 中(假设有两个控件的简单表单...如果需要,您可以随时循环浏览列表)我们设置 CausesValidation

    public bool ToggleValidate()
    {
        uneCalcValue.CausesValidation = !uneCalcValue.CausesValidation;
        txtDescription.CausesValidation = !txtDescription.CausesValidation;

        return txtDescription.CausesValidation;
    }

希望这会有所帮助。

This is an old question however I recently ran into this issue and solved it this way:

1st, we are loading a UserControl into a 'shell' Form that has a save and cancel button. The UserControl inherit an interface (like IEditView) that has functions for Save, Cancel, Validate and ToggleValidate.

In the shell form we used the mouse enter and mouse leave like so:

    private void utbCancel_MouseEnter(object sender, EventArgs e)
    {
        ((Interface.IEdit)tlpMain.Controls[1]).ToggleValidate();
    }

    private void utbCancel_MouseLeave(object sender, EventArgs e)
    {
        ((Interface.IEdit)tlpMain.Controls[1]).ToggleValidate();
    }

Then in ToggleValidate (Say a simple form with two controls...you can always just loop through a list if you want) we set the CausesValidation

    public bool ToggleValidate()
    {
        uneCalcValue.CausesValidation = !uneCalcValue.CausesValidation;
        txtDescription.CausesValidation = !txtDescription.CausesValidation;

        return txtDescription.CausesValidation;
    }

Hope this helps.

原野 2024-08-21 01:31:40

我今天在调查为什么我的表单在发生验证错误时不会关闭时发现了这个线程。

我在关闭按钮和表单本身上尝试了 CausesValidation = false (X 关闭)。

这种复杂的形式没有任何作用。

在阅读评论时,我发现一个似乎

在表单关闭事件上完美工作,而不是关闭按钮(因此当单击 X 时它也会触发)

这做到了这一点。

AutoValidate = AutoValidate.Disable;

I found this thread today while investigating why my form would not close when a validation error occurred.

I tried the CausesValidation = false on the close button and on the form itself (X to close).

Nothing was working with this complex form.

While reading through the comments I spotted one that appears to work perfectly

on the form close event , not the close button (so it will fire when X is clicked also)

This did the trick.

AutoValidate = AutoValidate.Disable;
冬天的雪花 2024-08-21 01:31:40

创建一个布尔值:

bool doOnce;

在函数中将其设置为 false,然后:

if (doOnce == false)
{
    e.cancel = true;
    doOnce = true;
}

这意味着它只会运行一次,并且您应该能够取消它。无论如何,这对我有用。

Create a bool:

bool doOnce;

Set it to false in your function and then:

if (doOnce == false)
{
    e.cancel = true;
    doOnce = true;
}

This means it will only run once and you should be able to cancel it. This worked for me anyways.

你穿错了嫁妆 2024-08-21 01:31:40

这对我有用。

private void btnCancelar_MouseMove(object sender, MouseEventArgs e)
{
    foreach (Control item in Form.ActiveForm.Controls)
    {
        item.CausesValidation = false;
    }
}

This work for me.

private void btnCancelar_MouseMove(object sender, MouseEventArgs e)
{
    foreach (Control item in Form.ActiveForm.Controls)
    {
        item.CausesValidation = false;
    }
}
丢了幸福的猪 2024-08-21 01:31:39

如果在编辑框失去焦点时进行验证,则取消按钮不会阻止这种情况发生。

但是,如果验证失败导致取消按钮无法执行其操作,请将按钮的 CausesValidation 属性设置为 false

参考:Button.CausesValidation< /code> 属性

If the validation occurs when the edit box loses focus, nothing about the the cancel button is going to stop that from happening.

However, if the failing validation is preventing the cancel button from doing its thing, set the CausesValidation property of the button to false.

Reference: Button.CausesValidation property

无风消散 2024-08-21 01:31:39

显然,按钮的 CausesValidation 属性必须设置为 false,然后单击时将永远不会发生验证事件。但如果按钮的父控件将其 CausesValidation 属性设置为 true,则此操作可能会失败。大多数时候,开发人员会错过/忘记更改容器控件(如面板控件)的CausesValidation 属性。将其也设置为 False。这应该可以解决问题。

Obviously CausesValidation property of the button has to be set to false and then the validating event will never happen on its click. But this can fail if the parent control of the button has its CausesValidation Property set to true. Most of the time developers misses/forgets to change the CausesValidation property of the container control (like the panel control). Set that also to False. And that should do the trick.

反目相谮 2024-08-21 01:31:39

我在关闭表单时遇到问题,因为某些控件的验证正在阻止它。我已经为取消按钮和取消按钮的所有父项设置了 control.CausesValidation = false 。但仍然遇到问题。

看起来,如果用户正在编辑使用验证的字段,并且决定放弃(使该字段保留无效输入),则会触发取消按钮事件,但窗口不会关闭。

此问题已通过取消按钮单击事件中的以下内容修复:

private void btnCancel_Click(object sender, EventArgs e)
{
    // Stop the validation of any controls so the form can close.
    AutoValidate = AutoValidate.Disable;
    Close();
}

I was having problems getting my form to close, since the validation of certain controls was stopping it. I had set the control.CausesValidation = false for the cancel button and all the parents of the cancel button. But still was having problems.

It seemed that if the user was in the middle of editing a field that was using validation and just decided to give up (leaving the field with an invalid input), the cancel button event was being fired but the window would not close down.

This was fixed by the following in the cancel button click event:

private void btnCancel_Click(object sender, EventArgs e)
{
    // Stop the validation of any controls so the form can close.
    AutoValidate = AutoValidate.Disable;
    Close();
}
誰ツ都不明白 2024-08-21 01:31:39

将“取消”按钮的 CausesValidation 属性设置为 false

Set the CausesValidation property of the Cancel button to false.

青朷 2024-08-21 01:31:39

CausesValidation 属性设置为 false

Set the CausesValidation property to false.

思慕 2024-08-21 01:31:39

这些答案都没有完全完成工作,但来自 的最后一个答案这个线程 确实如此。基本上,您需要:

  1. 确保“取消”按钮(如果有)将 .CausesValidation 设置为 false
  2. 重写此虚拟方法。

    受保护的覆盖 bool ProcessDialogKey(Keys keyData) {
        if (keyData == Keys.Escape) {
            this.AutoValidate = AutoValidate.Disable;
            CancelButton.PerformClick();
            this.AutoValidate = AutoValidate.Inherit;
            返回真;
        }
        返回base.ProcessDialogKey(keyData);
    }
    

我并没有真正回答这个问题,只是指出了实际上回答的两个人。

None of these answers quite did the job, but the last answer from this thread does. Basically, you need to:

  1. Insure that the Cancel button (if any) has .CausesValidation set to false
  2. Override this virtual method.

    protected override bool ProcessDialogKey(Keys keyData) {
        if (keyData == Keys.Escape) {
            this.AutoValidate = AutoValidate.Disable;
            CancelButton.PerformClick();
            this.AutoValidate = AutoValidate.Inherit;
            return true;
        }
        return base.ProcessDialogKey(keyData);
    }
    

I didn't really answer this, just pointing to the two guys who actually did.

国际总奸 2024-08-21 01:31:39

将 CausesValidation 设置为 false 是关键,但仅此还不够。如果按钮父级将 CausesValidation 设置为 true,则仍将调用验证事件。在我的一个案例中,我在表单的面板上有一个取消按钮,因此我必须在面板和表单上设置 CausesValidation = false。最后我以编程方式完成了这件事,因为它比遍历所有表格更简单......

Control control = cancelButton;

while(control != null)
{
   control.CausesValidation = false;
   control = control.Parent;
}

Setting CausesValidation to false is the key, however this alone is not enough. If the buttons parent has CausesValidation set to true, the validating event will still get called. In one of my cases I had a cancel button on a panel on a form, so I had to set CausesValidation = false on the panel as well as the form. In the end I did this programatically as it was simpler than going through all the forms...

Control control = cancelButton;

while(control != null)
{
   control.CausesValidation = false;
   control = control.Parent;
}
鸵鸟症 2024-08-21 01:31:39

就我而言,在表单中,我将属性 AutoValidate 设置为 EnableAllowFocusChange

In my case, in the form I set the property AutoValidate to EnableAllowFocusChange

愛上了 2024-08-21 01:31:39

通过使用 Visual Studio 向导,您可以这样做:

在此处输入图像描述

By using Visual Studio wizard you can do it like that:

enter image description here

半衾梦 2024-08-21 01:31:39

明智地使用 Control.CausesValidation 属性将帮助您实现您想要的目标。

Judicious use of the Control.CausesValidation property will help you achieve what you want.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文