Control Arrays

 Control Arrays

Programmers familiar with Visual Basic 6 are sometimes dismayed to find that the .Net designer doesn’t allow them to create arrays of controls – how can they get by without them?  Well, VB .Net does support control arrays, and they are just as easy to use as they were in VB6.

There are, however, a few differences.  The largest difference is that in VB6 you needed to either create all controls in your array using the designer, or create at least one so that you could add to the array in code.  In .Net, however, you can’t create an array using the designer, and it’s actually slightly simpler if you don’t create any of your array controls in the designer, but add them all using code.

There’s another difference that we will take advantage of in this example.  In .Net the controls don’t have to be in an array but can be part of any sort of collection, such as a Dictionary or List.  This example will create them as a List(Of T), which is simple to use and very powerful.  The following code creates six buttons across the bottom of the form.

The code also includes an example of how to create an event handler for these controls.  The event handler code can reference the control using the Sender variable from the parameter list.   If there is any need to reference the control outside of the event handler, use the list  reference – eg
Buttons(i).Text = “<whatever>”

 Dim Buttons As List(Of Button) = New List(Of Button)
 Dim ButtonCount As Integer = 6
 
 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
 
   For I As Integer = 1 To ButtonCount
     Dim B As Button = New Button
     B.Name = "btnInfo" & I.ToString
     Dim W As Integer = Me.Width \ (ButtonCount + 1)
     Dim X As Integer = (W + 1) * I - (W \ 2)
     Dim Y As Integer = Me.Height - 75
     B.Location = New Point(X, Y)
     B.Size = New Size(W, 20)
     B.Text = "Info #" & I.ToString
     B.Anchor = AnchorStyles.Bottom + AnchorStyles.Right
     AddHandler B.Click, AddressOf infoButton_Click
     Buttons.Add(B)
     Me.Controls.Add(B)
   Next
 End Sub
 
 Sub infoButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)
   Select Case sender.name
   Case "btnInfo1"
     'Code for handling button 1 click
   Case "btnInfo2"
     'Code for handling button 2 click
   '...
 End Select
 End Sub
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s