Wednesday, June 08, 2005

Create a Main subroutine to manage forms in a project (Visual Basic .NET)

If you have multiple forms in your project, you're probably tired of visiting the Property Pages dialog box to change the Startup Object each time you want to test a different form. However, you can save yourself a little aggravation by creating a Main module and loading your forms from it. First, to create a new module, select Project Add Module from your projects main menu. Then, add a subroutine named Main() to the code window. Inside the module, insert some code that will allow you to load one of the forms in your project, like we've done here:

Public Sub Main()
Dim myForm As Form
Dim formname As String
formname = InputBox("Please enter a form name", "Form1")
Select Case formname
Case "Form1"
myForm = New Form1
Case "Form2"
myForm = New Form2
Case Else
MsgBox("Form does not exist")
Exit Sub
End Select
myForm.ShowDialog()
myForm = Nothing
End Sub

In this code, we used an InputBox to choose a form and a Case statement to create a new Form object based on our form selection. The code loads the form with the ShowDialog method. While this code isn't the best or only way to accomplish this task, it's simple and effective. To automatically execute the Main module when you run your project, re-visit the Property Pages dialog box and change the Startup Object to Sub Main and click OK.

Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?