AfricaDotNet
www.AfricaDotNet.com Continues the .NET Conversation in Africa

Today's Byte #1 : Form Management

rated by 0 users
This post has 0 Replies | 2 Followers

Top 10 Contributor
Posts 40
Rad Posted: 05-20-2009 3:50 AM

In the lifetime of your application you undoubtedly create several forms and present them to the user. The code will invariably look as follows:

In C#

   1: //Create the form
   2: Form f = new FormUser();
   3: //Show the form
   4: f.Show()

In VB.NET

   1: 'Create the form
   2: dim f = new FormUser()
   3: 'Show the form
   4: f.Show()

Once you are done with the form, it will be automatcally disposed. Here's something you might be surprised to learn. If you display forms using the ShowDialog method rather than the Show method, you need to dispose of the forms yourself by invoking the Dispose method

In C#

   1: //Create the form
   2: Form f = new FormUser()
   3: //Show the form
   4: f.ShowDialog()
   5: //Dispose of the form
   6: f.Dispose()

In VB.NET

   1: 'create the form
   2: dim f as new FormUser()
   3: 'Show the form
   4: f.ShowDialog()
   5: 'Dispose of the form
   6: f.Dispose()

Alternatively, you can make use of the fact that the Form class implements th IDisposale interface. So you can rewrite the code as follows

In C#

   1: using(f = new FormUser())
   2: {
   3:     f.ShowDialog();
   4: }

In VB.NET

   1: Using f as new FormUser()
   2:     f.ShowDialog()
   3: End Using

Of course the question arises, why?

It's pretty simple actually. When you call ShowDialog, you are generally interested in the form you are showing passing back some value as a property, say the DialogResult, or some custom property. In which case the form must be kept in memory until you harvest the property. Since the runtime has no way of knowing when you have done this and are done with it, the form will be kept in memory until you explicitly call the Dispose method.

Till next time.

Rad.

Page 1 of 1 (1 items) | RSS
(c) AfricaDotNet
Powered by Community Server (Non-Commercial Edition), by Telligent Systems