开发者

How to skip Validating after clicking on a Form's Cancel button

开发者 https://www.devze.com 2022-12-13 21:37 出处:网络
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 bu

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 i开发者_运维知识库s 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?


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


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.


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();
}


Set the CausesValidation property of the Cancel button to false.


Set the CausesValidation property to false.


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.


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;
}


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


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

How to skip Validating after clicking on a Form's Cancel button


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


Just above the validation code on the edit box add:

if (btnCancel.focused)
  {
     return;
  }

That should do it.


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.


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);
    }


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.


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;


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.


This work for me.

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

精彩评论

暂无评论...
验证码 换一张
取 消