How do I add a common click event to a set of dynamically created controls? (2005 beta 2)

The code below works fine... except I want to hook the buttons to a
common event handled for click events. Sorry about the formatting...

Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim iX As Integer
Dim iY As Integer
Dim iNum As Integer
Dim objNew As Object
iNum = 1

'Creates an array of 100 buttons btnNum1 through btnNum100
For iY = 1 To 10
For iX = 1 To 10
objNew = New Button
objNew.Location = New Point((iX * 35) - 30, (iY * 25) - 20)
objNew.Size = New Size(30, 20)
objNew.Text = CStr(iNum)
'objNew.Click = ?
objNew.Name = "btnNum" & CStr(iNum)
Me.Controls.Add(objNew)
iNum += 1
Next
Next
End Sub
Private Sub Clicked(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
TextBox1.Text = "Clicked on button " & sender.Text & " called " & sender.Name
End Sub
End Class

[1020 byte] By [DanRhea33071] at [2007-12-16]
# 1
You can programmatically add event handlers using VB's AddHandler command. In your code snippet, just do the following:

1) Remove "Handles Button1.Click" from the event handler declaration.
2) In code add the following line to hook up the event handler to the button's click event.

AddHandler objNew.Click, AddressOf Clicked

That should do it.

-Sean

SeanDr_MS at 2007-9-9 > top of Msdn Tech,Visual Basic,Visual Basic General...
# 2
Use VB's AddHandler statement instead of the Handles clause.
See example below.

Option Strict On

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Dim iX As Integer

Dim iY As Integer

Dim iNum As Integer

Dim objNew As Button

iNum = 1

'Creates an array of 100 buttons btnNum1 through btnNum100

For iY = 1 To 10

For iX = 1 To 10

objNew = New Button

objNew.Location = New Point((iX * 35) - 30, (iY * 25) - 20)

objNew.Size = New Size(30, 20)

objNew.Text = CStr(iNum)

AddHandler objNew.Click, AddressOf Me.Clicked

objNew.Name = "btnNum" & CStr(iNum)

Me.Controls.Add(objNew)

iNum += 1

Next

Next

End Sub

Private Sub Clicked(ByVal sender As System.Object, ByVal e As System.EventArgs)

Dim btn As Button = CType(sender, Button)

TextBox1.Text = "Clicked on button " & btn.Text & " called " & btn.Name

End Sub

End Class

JohnRi at 2007-9-9 > top of Msdn Tech,Visual Basic,Visual Basic General...
# 3
Thanks John...

I almost missed the change of "objNew" from "Object" to "Button". It's working great now!

Now to search for "how to post formatted code into the forums". :-)

Dan Rhea

DanRhea at 2007-9-9 > top of Msdn Tech,Visual Basic,Visual Basic General...