p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   BOOK: Stephens' C# Programming with Visual Studio 2010 24-Hour Trainer (http://p2p.wrox.com/forumdisplay.php?f=574)
-   -   Lesson 9 Tryit (http://p2p.wrox.com/showthread.php?t=87988)

cellison July 13th, 2012 05:04 PM

Lesson 9 Tryit
In the TryIt for Lesson 9, you create other forms from the main form. Because you take the instantiation of the forms outside of the button click event (and place it in the main form's loading function), you run into a situation where if one of the windows is closed, and then the button is invoked again, an exception is thrown because you are attempting to do a "Show()" on an instance that no longer exists. It will do this on any of the buttons for which a window is opened and then subsequently closed.

I know there are number of ways to handle this, such as creating a new instance on each button click (bring the instantiation back into the event itself)... Of course, this has the sometimes undesirable effect of enabling the user to generate a bunch of windows and only be able to actively take information from the last one. You could also check for the existence of the form, I guess.

What is the accepted best practice to do this in C# when I want a single form for each button, especially if you have one such as your data entry form in the database chapters, and you have to ensure that things are saved during the "closing" event?

Rod Stephens July 14th, 2012 01:57 PM

Hi cellison,

I think a later chapter deals with the problem of the main form trying to repost a form that has been destroyed.

For modal dialogs, by far the most common strategy is to make the button's Click event handler create a new form every time. That resets the form so you know it is in its starting state and more importantly keeps everything local so you don't have those class-level form instances floating around to confuse people.

If data needs to be saved and used to initialize the dialog before it is displayed, the main form stores it somewhere in variables.

People sometimes use another strategy for forms that are not modal dialogs. For example, suppose you have a bunch of secondary forms that the user may want to display often, possibly at the same time. In that case you can use the approach followed by Lesson 9.

To prevent the form from being destroyed, you can make the FormClosing event handler cancel the close and hide the form. Note that with this approach, you cannot easily "cancel" the form.

I'll post some examples in the next couple days on C# Helper.

All times are GMT -4. The time now is 01:16 AM.

Powered by vBulletin®
Copyright ©2000 - 2019, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.