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.
|
If there are several forms within a project where all of them are already created. How do I load one form from another?