Control Arrays are arrays of controls sharing a common event handler. That is, you need to write code for only one event, which can handle other controls' events.
For example if you consider an application like calculator, where on the click event of the buttons from 0 to 9, you want to append the text to the visible text. So when you write code for all individual buttons, it is a time consuming process. Because we need the same peace of code for all these buttons, we can create one event handler to handle the events raised by all these buttons.
In Visual Basic 6, this was fairly simple. You have to copy and paste the control and confirm ‘Yes’ when asked, whether to create a control array. You can see the first control automatically gets an index of zero and the following controls get the index incremented by one from the last control. And if you double click on the buttons, you can see all these controls have same event handler, however you can notice a new argument, which is passed to the click event, named Index. This index property is the one, which will tell you which button is clicked (If you want to know, which one clicked). To create this while runtime, you can copy one control at design time and use this button to create other buttons. You can load a control and remove a control dynamically in VB6.
In Dot net the creation of control arrays are easier than the previous versions and are not created by copying and pasting, instead simply add the control events to the Handles list. You can give any name to this procedure.
Private Sub ClickButton(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click, _
Dim btn As Button
btn = CType(sender, Button)
In the above example
ClickButton procedure is handling the click event of
Enter event of the
Button3. In order to check the control that is pressed, you need to convert the sender to the respective type. The
CType function converts it into a button type, so that you can access the attributes of the event raised by the control.
Now let us see how to create a button in run time,
Dim btn As New Button()
location and the size
btn.Location = New System.Drawing.Point(200, 30)
btn.Size = New System.Drawing.Size(100, 20)
btn.Text = "New Button"
AddHandler btn.Click, AddressOf Me.ClickButton