I want to validate input on two textboxes on my form if the user clicks the close/"red X" button. I assigned an event handler to the FormClosing property of the Form, but when I click it, the program goes into an infinite loop and then throws the stack overflow exception. Here is my code:
private bool _Cancel(object sender, EventArgs e)
{
if (((this.textboxFirstName.Text != null) && (this.textboxFirstName.Text != string.Empty))
|| ((this.textboxLastName.Text != null) && (this.textboxLastName.Text != string.Empty)))
{
DialogResult pResult = MessageBox.Show("Do you want to cancel adding this driver?", "Warning", MessageBoxButtons.YesNo);
if (pResult == DialogResult.Yes)
{
this.Close();
return true;
}
else return false;
}
else
{
this.Close();
return true;
}
}
private void AddDriver_Window_FormClosing(object sender, FormClosingEventArgs e)
{
if (!this._Cancel(sender, e))
e.Cancel = true;
}
What am I doing wrong? As far as I know, if I set the Cancel property to true the form should cancel closing. MS' documentation is no help...
EDIT: Is it bad practice to piggyback onto the EventArgs e
passed in the call to this._Cancel
and send a e.CloseReason
that I specify? The reason why I originally had the this.Close()
is because this handler was originally written for a cancel button on the form (different from the close button). I wanted to reuse the code, so I was thinking of checking this parameter in the _Cancel
method to determine if this.Close()
should be called.
EDIT 2: Nevermind figure I can just check if the e.CloseReason is "UserClosing"