Monday, September 10, 2007

DialogResult - Remember to Keep It None

If you don't want to look for the place in code where your modal dialog gets unexpectedly closed before you want it to - remember to set all buttons' DialogResult property to None!

Everyone applies the 'copy-paste' rule from time to time - especially when creating Windows forms. You need another button of the same size - you just copy it and paste it, don't you?

Well - you have to watch out! As you might expect - most of the values of the new button's properties are the same as those of the old one.
That's good as long as you don't copy an OK button and use it as an ordinary button.

An OK button has its DialogResult property set to "OK" (oh, really?).
Now, according to

If the DialogResult for this property is set to anything other than None, and if the parent form was displayed through the ShowDialog method, clicking the button closes the parent form without your having to hook up any events. The form's DialogResult property is then set to the DialogResult of the button when the button is clicked.

So - if you copied the OK button and pasted it as some other button, say, "Refresh", that's fine.
Then you write some code handling that button's Click event, e.g. you want it to reload contents of some list on the form.
Now look what happens when you actually click the "Refresh" button: the Click event handler does get executed (the list gets refreshed), but right after that the form is closed!

If you were debugging the Click event handler, you finally go out of that method's scope and all of a sudden - you find yourself on the form.ShowDialog() statement.

It tooks me some time to finally find out what was going on! :)

No comments: