65.9K
CodeProject is changing. Read more.
Home

How to Create Control Array with Event

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (1 vote)

Mar 22, 2011

CPOL
viewsIcon

14612

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.
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