Export (0) Print
Expand All
Expand Minimize

Event may fire when form is initialized

Visual Studio .NET 2003

In Visual Basic 6.0, events for a form or control were not raised until the form was finished loading. In Visual Basic .NET, the InitializeComponent method handles the initialization of the form and its controls; the order in which objects are initialized cannot be modified. In some cases, this may cause events to be raised during initialization. If the event handler references other components that have not yet been initialized, this could cause a run-time error.

For example, if the Click event handler for a CheckBox control sets a value in a TextBox control, an error may occur if the TextBox control is not yet initialized:

' Visual Basic 6.0
Private Sub Check1_Click()
   TextBox1.Text = "Check1 was clicked"
End Sub

' After upgrade to Visual Basic .NET
' UPGRADE_WARNING: Event CheckStateChanged may fire when form is initialized.
Private Sub Check1_CheckStateChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Check1.CheckStateChanged
   ' The following line will cause an error if TextBox1 is not
   ' initialized.
   TextBox1.Text = "Check1 was clicked"
End Sub

What to do next

  1. Add an IsInitializing property to the form.
  2. Set the property to true in the form's constructor just prior to the InitializeComponent call; set it to false immediately following the call.
  3. Add the following logic to the event procedure to check the value of the property before running the code:
    Private Sub Check1_CheckStateChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Check1.CheckStateChanged
       If Form1.DefInstance.IsInitializing = True Then
          Exit Sub
       Else
          TextBox1.Text = "Check1 was clicked"
       End If
    End Sub
    

See Also

Property Statement | Forms Changes in Visual Basic .NET

Show:
© 2015 Microsoft