Question

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"

Was it helpful?

Solution

Ali why are you call

 if (pResult == DialogResult.Yes)
     {
         this.Close();
         return true;
     }
     else return false;

in case the dialog box = vbyes return true or false as per your need in example

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)
         {
             //avoid => this.Close();
             return true;
         }
         else return false;
      }
      else
     {
         // avoid => this.Close();
         return true;
 }

}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top