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

前端 未结 17 1150
一生所求
一生所求 2020-12-08 04:04

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. Wh

相关标签:
17条回答
  • 2020-12-08 04:48

    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);
        }
    
    0 讨论(0)
  • 2020-12-08 04:49

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

    0 讨论(0)
  • 2020-12-08 04:51

    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.

    0 讨论(0)
  • 2020-12-08 04:51

    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.

    0 讨论(0)
  • 2020-12-08 04:52

    Set the CausesValidation property of the Cancel button to false.

    0 讨论(0)
提交回复
热议问题