Dynamically adding array of buttons to form

H

Hrvoje Vrbanc

Hello all,

I'm relatively inexperienced with Windows Forms programming so I have one
question: what is the best way to dynamically add e.g. 100 buttons in 10 x
10 pattern, each button with different text (numbers from 1 to 100), but
with very similar event handlers (each time a certain number is compared
with the text of the button).

I have tried basically the following:

Dim i As Integer
Dim bt(10) As Button
For i = 1 To 10
bt(i).Size = New System.Drawing.Size(35, 25)
bt(i).Text = i
Me.Controls.Add(bt(i))
Next

There were some errors.

I would be grateful for any help!
Hrvoje
 
E

Ed Kaim

Here's some code that will set up the screen as you've desribed (without the
events hooked up):
Dim bt(10, 10) As Button

Dim x, y As Integer

For y = 0 To 9

For x = 0 To 9

bt(x, y) = New Button

bt(x, y).Text = String.Format("{0},{1}", x, y)

bt(x, y).Size = New Size(35, 25)

bt(x, y).Location = New Point(40 * x, 30 * y)

Me.Controls.Add(bt(x, y))

Next

Next
 
H

Hrvoje Vrbanc

Thank you Ed, that's exactly what I needed!
Now, how to hook up the onClick event to every button?

Thanks,
Hrvoje
 
E

Ed Kaim

Supposed you have an event handler like:
Private Sub Buttons_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs)

MessageBox.Show(sender.ToString())

End Sub

Then you'd want to change the setup code to something like:
Dim bt(10, 10) As Button

Dim x, y As Integer

For y = 0 To 9

For x = 0 To 9

bt(x, y) = New Button

bt(x, y).Text = String.Format("B{0},{1}", x, y)

bt(x, y).Size = New Size(35, 25)

bt(x, y).Location = New Point(40 * x, 30 * y)

AddHandler bt(x, y).Click, AddressOf Buttons_Click

Me.Controls.Add(bt(x, y))

Next

Next

(Note the AddHandler that points to the event handler for Click).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top