Visual Basic Reference

Controls Collection

See Also    Example    Properties    Methods    Events

A collection whose elements represent the controls on a component. The Controls collection has a Count property which specifies the number of controls in the collection, and an Item method which returns a member of the collection.

Syntax

object.Controls.Count

object.Controls(index)

The Controls collection syntax has these parts:

Part Description
object An object expression that evaluates to an object in the Applies To list.
Index An integer with a range from 0 to Controls.Count - 1.

Note   If the component is a Visual Basic module, such as a Form or UserControl, you don't have to supply the object expression when writing code within the module. If the container is a compiled ActiveX control, such as a ToolBar control, however, you must always supply the object expression.

Remarks

The Controls collection enumerates loaded controls on a component and can be useful for iterating through them. For example, you might use it to change the BackColor property of all the Label controls on a Form.

The Controls collection identifies an intrinsic form-level variable named Controls. If you omit the optional object placeholder, you must include the Controls keyword. However, if you include object, you can omit the Controls keyword. For example, the following two lines of code have the same effect:

MyForm.Controls(6).Top = MyForm.Controls(5).Top + increment
MyForm(6).Top = MyForm(5).Top + increment

You can pass Controls(index) to a function whose argument is specified as a Controls class. You can also access members using their name. For example:

Controls("Command1").Top

You can use the TypeOf keyword with the If statement, or the TypeName function, to determine the type of a control in the Controls collection.

Note   The Controls collection is not a member of the Visual Basic Collection class. It has a smaller set of properties and methods than a Collection object, and you cannot create instances of it.