Wednesday, December 12, 2012

Control array in visual basic


Control Arrays: As you have seen, arrays can have many data types. In addition to customary data types, Visual Basic supports the concept of control arrays. You can think of this array type as an array of objects, or in this case, an array of controls. Control arrays support all types of Visual Basic controls.
To create a control array in Visual Basic during design time, simply add a control to your Form. Next, copy the control using either menu options or keyboard shortcuts, and paste the copy in memory to the same Form. A dialog box should appear asking whether you want to create a control array. After you select Yes in the dialog box, the new control is added and your control array is created. After which, you can continue to add controls to the array by pasting until you have the desired amount.
When a control becomes part of a control array, its name remains that of the control array, with an element or index indicating its specific identity.
Set all necessary control properties before making a control array. Otherwise, you will have to set control properties for each control in the array.
Double-clicking on any control in the array produces the same event. These shared events pass an index as an argument that you can use to identify each control in the array:
Private Sub Command1_Click(Index As Integer)
Command1(1).Caption = “Index 1”
End Sub
Beyond design time, Visual Basic offers a more dynamic approach to control arrays in runtime. During runtime, you can dynamically add controls and remove controls from a control array. You add and remove these dynamic controls using the Load and Unload statements:
Load ObjectName(Index)
If you want to load a control into a control array, you first must create the array in design time.
When you unload controls from a control array, the index must be a valid index; otherwise, Visual Basic generates an error:
Unload ObjectName(Index)

Why would you want an array of controls? Well, in short, you might want an array ofcontrols for the same reason you would want any other array, such as creating and maintaining less code or combining like data (in this case, like controls). Beyond programming esthetics, control arrays offer the benefit of shared procedures and events.