Previous | Index | Next 

[PRB] Accessing a control from the Initialize event handler causes a NullReference exception

Under VB6, it was ok to reference a control from inside the Form_Initialize event hander, even though this technique wasn’t recommended because it forced the loading of the control and indirectly fired the Load event before completing the execution of the Initialize event.

Inside migrated .NET project, accessing a control from inside the Form_Initialize event doesn’t indirectly load the control; instead, it causes a NullReference error. For this reason, you must move the reference to another place in the migrated code, for example in the Form_Load event handler.

Likewise, you can’t reference an item of a control array from inside the Form_Initialize event handler, because the actual control array hasn’t been created yet. This detail is quite clear if you look at the code that has been generated in the *.Designer.vb file for each given form:

    ' This method wraps the call to InitializeComponent, but can be called from base class.
    Protected Overrides Sub InitializeComponents()
      Me.ObjectIsInitializing = True
      InitializeComponent()
      ' Initialize control arrays.
      Me.LblSelection = New CodeArchitects.VB6Library.VB6ControlArray(Of _
        CodeArchitects.VB6Library.VB6Label)(LblSelection_001, LblSelection_002)

You can work around this limitation in two ways. First, you can directly reference the controls that belong to the control array (LblSelection_001 and LblSelection_002, in previous example).

Second, if you aren’t sure about when a given piece of code executes, you can test the ObjectIsInitializing property that all VB6Form instances expose, and avoid referencing the control array if this property is True, as in:

    If Not Me.ObjectIsInitializing Then
      ' here it is save to access the LblSelection control array
      ' ...
    End If

 

Previous | Index | Next