Previous | Index | Next 

[PRB] Form-level variables in default forms don’t retain their values between calls

In the attempt to simplify the migration from VB6, Microsoft introduced the support for default form instances in VB2005. However, this feature isn’t complete and still creates many problems.

One of such problems is that, even if the code appears to be referencing the same form instance, it actually creates a new form each time the form is shown. To prove this point, consider the following VB.NET code:

        ' inside Form1
        Private Sub Form_Load() Handles MyBase.Load
            ' assign a variable belonging to Form2
            Form2.UserName = "John Doe"
        End Sub
  
        Private Sub Command1_Click() Handles Command1.Click
            ' load  and show Form2, but also display it’s handle
            Debug.PrintLine(Form1.Handle.ToInt32())
            Form2.Show()
        End Sub

If you click Command1, then close the second form that appears, and click Command1 again, you will notice that the form’s handle is differente, which in turn proves that you are dealing with two different instances, even though both were accessed through the Form2 variable.

As a consequence for this fact, the second instance of Form2 will have its UserName variable set to an empty string. If your code assumes that the UserName variable value is preserved between calls you are in trouble.

The simplest way to work around this issue is to move the UserName variable into a BAS module (before the migration) or to a VB.NET Module (after the migration), so that its value is preserved between calls.

 

Previous | Index | Next