Reputation: 821
I'm encountering strange behaviour from my WinForms app in VS 2010. I launch a new form using straight-forward code:
MainDisplayForm.cs:
using (MyForm myForm = new MyForm())
{
var result = myForm.ShowDialog();
if (result == DialogResult.OK)
{
// do stuff
}
}
I added a Cancel button to MyForm that displayed a confirmation MessageBox
to the user and then called this.Close()
. I later removed the this.Close()
line because I added a dedicated Close button. However, whenever I press Cancel the instance of MyForm still closes!
MyForm.cs:
private void cmdCancel_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show( ... )
// clear the form if user really wants to quit
// this.Close()
// even after removing the above line, program still jumps to FormClosing
}
When I debug line-by-line after clicking on the Cancel button, the program flow just jumps to MyForm_FormClosing
after it hits the end of cmdCancel_Click
. I created a new button and set its click event to cmdCancel_Click
and it did not close the form - so the problem is solved, but I am still wondering if this is just a bug, or something else? I also made sure to reset the DialogResult
property of my Cancel button back to None
(after changing it to Cancel
before I introduced the dedicated Close button).
Upvotes: 0
Views: 103
Reputation: 5908
When exiting the scope of 'using' statement, it calls 'myForm.Dispose()' (that's the whole point of 'using' - to make sure Dispose()is called). This in turn destroys 'myForm' instance, including closing the window.
Upvotes: 1