user228985
user228985

Reputation: 501

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

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?

Upvotes: 50

Views: 57356

Answers (18)

Tony H
Tony H

Reputation: 101

I found that setting the CausesValidation property of the Cancel control did not solve the problem when I pressed the Cancel button in the middle of the edit of a Textbox.

I solved the problem by checking the Form's ActiveControl property at the start of the Testbox's Validating event procedure. If the ActiveControl was the Cancel button, I aborted the validation.

Unfortunately you have to do this in the Validating event procedures of many Controls in the Form.

Upvotes: 0

Joseph Hulme
Joseph Hulme

Reputation: 13

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.

Upvotes: 0

TruAG
TruAG

Reputation: 41

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;

Upvotes: 0

melegant
melegant

Reputation: 1709

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.

Upvotes: 0

Oscar Castiblanco
Oscar Castiblanco

Reputation: 1646

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

enter image description here

Upvotes: 3

Alecs
Alecs

Reputation: 2920

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

Upvotes: 3

TonyM
TonyM

Reputation: 191

Just above the validation code on the edit box add:

if (btnCancel.focused)
  {
     return;
  }

That should do it.

Upvotes: 2

user4938759
user4938759

Reputation: 1

This work for me.

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

Upvotes: -2

Adiono
Adiono

Reputation: 1044

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

Upvotes: 0

Wade Hatler
Wade Hatler

Reputation: 1835

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.

Upvotes: 4

Ben
Ben

Reputation: 3391

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

Upvotes: 25

Olivier de Rivoyre
Olivier de Rivoyre

Reputation: 1597

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.

Upvotes: 1

Vimal Raj
Vimal Raj

Reputation: 1038

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.

Upvotes: 38

Steve Sheldon
Steve Sheldon

Reputation: 6611

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

Upvotes: 3

Daniel Schaffer
Daniel Schaffer

Reputation: 57822

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

Upvotes: 54

to StackOverflow
to StackOverflow

Reputation: 124696

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

Upvotes: 2

Brandon
Brandon

Reputation: 69953

Set the CausesValidation property to false.

Upvotes: 4

womp
womp

Reputation: 116977

Set the CausesValidation property of the Cancel button to false.

Upvotes: 19

Related Questions