How to Create Control Array with Event

Updated PdotWang 2 Tallied Votes 880 Views Share

I want to create 100 buttons in a Form. This is what I just tested.
When you finish the following steps, you will see it is very nice. 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
    'Use 0 based array
    Private NRow As Integer = 9
    Private NCol As Integer = 9
    Private BtnArray((NRow + 1) * (NCol + 1) - 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 + 1), i \ (NCol + 1))
            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
Member Avatar for Dukane
Dukane

Helpful for a current project! Thank you!

Reverend Jim 4,678 Hi, I'm Jim, one of DaniWeb's moderators. Moderator Featured Poster

You say make it 10x10 with 10% each. This is the first time I am using the TableLayout panel. I am able to determine (faily easily) that "make it 10x10" means set RowCount=10 and ColumnCount=10. However "with 10% each" is not as clear. Perhaps you could spell this out specifically in terms of how this is done. There are a lot of novice programmers who could use some hand holding and sample code should not leave anyone guessing.

Specifically, to set to 10% each means

Click on "..." in the Columns (collection) property. In the Column and Row Styles dialog, select all columns. In the Size Type panel, select "percent" and set to 10.00. To set rows to 10& do the same but in the Rows (collection) property.

jaimin4829 0 Newbie Poster

I want to create 100 buttons in a Form. This is what I just tested.
When you finish the following steps, you will see it is very nice. 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.

nice quot dear like it..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.