Simplify your business
Monday, 13 October 2008 10:39 pm

Form loading trap in VB.NET

Friday, 21 April 2006  

One of the first problems a VB6 developer encounters when migrating to VB.NET is that the way forms are loaded has changed completely. Although this (typical) VB6 method of loading the main application form is syntactically correct, it will definitely not produce the desired result:

Module Functions
   Public Sub Main()
      Dim F As New MainForm
      F.Show()
   End Sub
End Module

In VB6, this would load and display an instance of a form named “MainForm”. In VB.NET, it would do exactly the same but then immediately afterwards would close the form and terminate the application.

Why?

The problem is that VB.NET treats the object “F” as a local instance of the “MainForm” class, which is destroyed as soon as the startup method Main() is exited. The solution is to use the Application.Run() method instead and take advantage of the built-in function overloading facilities that the .NET framework provides:

Module Functions
   Public Sub Main()
      Dim F As New MainForm
      Application.Run(F)
   End Sub
End Module

Did I fall for the same trap when I started out in VB.NET? Bloody oath I did.

 one comment:

  1. bikash - Saturday, 23 June 2007 6:28 pm  

    If there are several forms within a project where all of them are already created. How do I load one form from another?


Got something to say?

To protect your privacy, your email address will not be displayed.





Some basic rules for commenting:

  • Watch your language.
  • Keep comments on-topic and relevant.
  • You can use basic XHTML tags for formatting and linking but not bbcode.
  • Comments are moderated, so don't double post if your comment doesn't appear immediately.
  • Please proof-read your comments for spelling and grammar mistakes.
  • Watch your language.