2007/11/07

Closing a windows form

How to close a windows form? Many people will create a click event and call the Form class' Close() method like this:
private void btnExit_Click(object sender, EventArgs e)
{
  this.Close(); //or this.Dispose();
}

Since you created the Click event just for closing the form, why don't we try other simpler approach? We can set the button's DialogResult property to a non-default value (any value other than None), so that .Net framework will close the form for us automatically when user click that button. This way we can handle button clicks without an event handler. Actually the DialogResult property will return a value depends on how the form is closed, and we can use that value to do many things.

What if we also have an event handler for the same button's Click event? Well, the Click event will still be executed, and it will be done first. After the event finishes and returns control to framework, the form will be closed.

By the way, this cannot replace the Application.Exit(). Don't waste your time on using the button's DialogResult property on the main form's Exit button, it won't work.

If you want to know more details about what's underlying, I'll suggest you to read this book: .NET Windows Forms in a Nutshell.

No comments:

Post a Comment