Search code examples
c#winformsvalidating-event

Skipping validation for closing the form from the controlbox


I have a simple form with a textbox and I want to make the user to enter some data in the textbox before closing or skipping this control,but when I handle the validating event I 'm only able to close the form by putting a Cancel Button with CauseValidation property set to true.My question is that How can I enable the X button in control box for closing the form even when nothing is written in the textbox?By adding the form_closing handler,this button works the second time that I click it,but can I close the form by pressing the X button only once?

Here is my form.cs file:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;

    namespace Validation
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();

            }

            private void textBox1_Validating(object sender, CancelEventArgs e)
            {

                if(textBox1.Text.Trim().Equals(string.Empty))
                {
                e.Cancel=true;

                errorProvider1.SetError(textBox1,"Error");

                }
                else
                    errorProvider1.SetError(textBox1,"");
            }
       private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            textBox1.CausesValidation = false;
        }
        }
    }

Thanks a lot


Solution

  • yes, try this one.

      private void Form2_FormClosing(object sender, FormClosingEventArgs e)
            {
                if (textBox1.CausesValidation)
                {
                    textBox1.CausesValidation = false;
                    Close();
                }
            }