Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / VB

How to Create Control Array with Event

4.00/5 (1 vote)
23 Mar 2011CPOL 14.5K  
Add to Layout, and Add Event
I want to create 100 buttons in a Form. This is what I just tested.

I do have the images and I want to show you, but I could not attach those very nice pictures. When you finish the following steps, you will be able to see it. Enjoy.

Step 1: Create a Form called Form1.
Step 2: Add a TableLayoutPanel called TableLayoutPanel1.
Step 3: Make it 10 X 10 with 10% each.
Step 4: Set its anchor to T, B, L, and R. (It could be in any size in design time)
Step 5: Copy the code to Form1.vb.
Step 6: Run it, and you get it.

VB
Public Class Form1
    Private NRow As Integer = 10
    Private NCol As Integer = 10
    Private BtnArray(NRow * NCol - 1) As Button
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        TableLayoutPanel1.Size = Me.ClientSize
        For i As Integer = 0 To BtnArray.Length - 1
            BtnArray(i) = New Button()
            BtnArray(i).Anchor = AnchorStyles.Top Or AnchorStyles.Bottom Or AnchorStyles.Left Or AnchorStyles.Right
            BtnArray(i).Text = CStr(i)
            TableLayoutPanel1.Controls.Add(BtnArray(i), i Mod NCol, i \ NCol)
            AddHandler BtnArray(i).Click, AddressOf ClickHandler
        Next
    End Sub
    Public Sub ClickHandler(ByVal sender As Object, ByVal e As System.EventArgs)
        MsgBox("I am button #" & CType(sender, Button).Text)
    End Sub
End Class

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)