In Visual Basic 6.0, the Controls collection was a collection whose elements represented the controls on a form or container control. In Visual Basic .NET, the System.Windows.Forms.Control.ControlCollection class replaces the Controls collection. Forms have a default ControlCollection class that can be accessed using the syntax Me.Controls.
There are some differences in behavior:
- In Visual Basic 6.0, the Add method of the Controls collection was late-bound; controls were created in the Add method by specifying the control class as an argument. In Visual Basic .NET. the Add method of a Controls collection class requires that the controls have already been created before being added to the collection.
Note Because of this and other differences between Visual Basic 6.0 and Visual Basic .NET Controls collections, calls to the Add method are not upgraded. You must add code to recreate your application's behavior using the new Controls.Add method.
- In Visual Basic 6.0, the Timer and Menu controls were members of the Controls collection. In Visual Basic .NET they are replaced by the Timer and MainMenu components; components are not members of the ControlCollection class.
- The Controls collection included controls that were children of a container control (for example, controls sited on a Frame control); the ControlCollection class does not.
- Members of the Controls collection could be referenced using either the index or the name of the control; the ControlCollection class only supports the index.
- The Remove method of the Controls collection could only be used for controls that had been added using the Add method; the ControlCollection class does not have this restriction.
The following example illustrates some of the differences:
' Visual Basic 6.0
Private Sub Command1_Click()
Dim c As Control
Set c = Controls.Add("VB.TextBox", "Text1")
c.Visible = True
c.Text = "Hello"
If Controls.Count > 1 Then
MsgBox (Controls("Text1").Text)
End If
' The following line causes a compilation error.
Controls.Remove (Command1)
End Sub
' Visual Basic .NET
Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click
Dim textBox1 As New System.Windows.Forms.TextBox
textBox1.Text = "Hello"
Me.Controls.Add(textBox1)
If Me.Controls.Count > 1 Then
MsgBox(Me.Controls(Me.Controls.IndexOf(textBox1)).Text)
End If
Me.Controls.Remove(button1)
End Sub
See Also
Control.Controls Property | Form.ControlCollection Class