Previous | Index | Next 

[HOWTO] Speed up For Each loops that iterate over the Controls collection

Iterating over all the controls on a form is a common operation in VB6 apps. For example, the following code clears the caption of all Label controls:

        Dim ctrl As Control
        For Each ctrl in Me.Controls
            If TypeOf ctrl Is Label Then ctrl.Caption = ""
        Next

VB Migration Partner converts the code as-is, replaces the Control variable with an Object variable:

        Dim ctrl As Object
        For Each ctrl in Me.Controls6
            If TypeOf ctrl Is VB6Label Then ctrl.Caption = ""
        Next

The replacement is necessary for two reasons. First, the Controls6 collection can include components (e.g. Timer and CommonDialog) which would cause a TypeMismatch exception if assigned to a System.Windows.Forms.Control variable. Second, using an Object variable avoids compilation errors when accessing the Caption property or another member that isn’t exposed by the .NET Control class.

Even if VB Migration Partner renders Control variables as Object variables by default, in some cases using the .NET Control class would work correctly and would deliver more efficient code because early binding would be used instead. More precisely, you should force VB Migration Partner to convert Control variables to System.Windows.Forms.Control variables if the following two conditions are both met:

  1. the form doesn’t contain nonvisible components such as Timer, Menu, or CommonDialog or you aren't interested in processing these components 
  2. the code inside the loop references members that are exposed by the .NET Control class.

You can force VB Migration Partner to convert a given Control variable to a System.Windows.Forms.Control variable by means of the SetType pragma, as in this code snippet:

        '## ctrl.SetType Control
        Dim ctrl As Control
        For Each ctrl in Me.Controls
            If TypeOf ctrl Is TextBox Then ctrl.Text = ""
        Next

Alternatively, you can convert all Control variables in the current file or project with the ChangeType pragma:

        '## project:ChangeType Control, Object

 

Previous | Index | Next