Ben
Ben

Reputation: 2523

Check if Form is closing

I have a method that fires on a "Leave" event:

private void cmbBox1_Leave(object sender, EventArgs e)
{
    bool error = true;

    if (something == true)
    { 
        //do stuff...
        error = false;
    } 

    if (error == true)
    {
        MessageBox.Show("Error!")
    }
}

Problem is, that closing the form counts as "leaving focus" from the control, so when I close the form, the message box pops up. Is there a way I can catch the Form closing as an invalid parameter? I.e.

if (error == true && this.FormClosing == false)
{
    MessageBox.Show("Error!")
}

Upvotes: 0

Views: 1190

Answers (1)

Blorgbeard
Blorgbeard

Reputation: 103467

Try using the Validating event instead of Leave.

Then in FormClosing, you can set this.AutoValidate = AutoValidate.Disable; and your validation won't be fired any more.

If you close the form via an OK or Cancel button, you may need to set CausesValidation = false on those buttons as well (maybe you want validation on OK, though).

Upvotes: 1

Related Questions