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

前端 未结 17 1232
一生所求
一生所求 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);
        }
    

提交回复
热议问题