Validation of input elements and Form Closing

One of very often questions ask by WinForms developers is “How to make sure that if Form is Closing, no validation occurs in contained controls”?

For reference, validating input is rather straightforward:

1. Add ErrorProvider to Form
2. For control in question, add handlers for Validating and Validated events:


        private void tbFixPath_Validating(object sender, CancelEventArgs e)
        {
            if (!ControlValidated(tbFixPath.Text))
            {
                // Cancel the event and select the text to be corrected by the user.
                e.Cancel = true;
                tbFixPath.Select(0, tbFixPath.Text.Length);

                // Set the ErrorProvider error with the text to display. 
                this.errorProvider1.SetError(tbFixPath, 
                   "Sorry, something went wrong during validation. Please check.");
            }
        }

        private void tbFixPath_Validated(object sender, EventArgs e)
        {
                // After successful validation, clear error message.
                errorProvider1.SetError(tbFixPath, "");
        }

3. Everything is fine, until user tries to close form where some input elements are not validated – closing will fail. In order to prevent this, if you are absolutely sure that you want to close such form, just add:


        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
                e.Cancel = false;
        }

so that no cancellation of closing event will occur.

I know that this is basic 🙂 but after I was ask for 10th time in 6 months, I figured that is better to note this somewhere 🙂

2 thoughts on “Validation of input elements and Form Closing”

  1. Thank you. I was working on a hack suggested on another site which made use of System.Diagnostics.StackFrame! Although in hindsight this seems obvious, it didn’t occur to me.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.