The included zip file contains complete source code of a vb.net windows forms
project that contains 2 command buttons and a textbox when you run it. Entering
an amount of controls to create and clicking the create button adds the selected
amount of command buttons and links their click event to the design time command
button.
When you click any of the dynamically created buttons or the design time button
the same event procedure checks to see which control was clicked and informs
you.
The key parts to the source code are:-
1. The DesignTime button's click event
Private Sub cbDesignTime_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles cbDesignTime.Click
'get a reference to the sender onjects name
Dim cName As String = CType(sender, System.Windows.Forms.Button).Name
'check to see which control was clicked by name
If cName = "cbDesignTime" Then
MsgBox("You clicked the Button placed here in design
time")
Else
Dim x As Integer
For x = 0 To cbCount
If cName = "RunTime" & x Then
MsgBox("You clicked RunTime" &
x & " button")
End If
Next
End If
End Sub
CType is a function which casts the sender object into whatever object you need
if possible, in this case a button and we can then reference the name of the
clicked button and use standard code to check for each name.
2. The CreateControls button click code
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim x As Integer
'create controls for the amount in the textbox
Try
For x = 0 To CType(tbButtonAmount.Text, Integer) -
1
Dim cb As New System.Windows.Forms.Button()
cb.Size = New System.Drawing.Size(200,
30)
cb.Location = New System.Drawing.Point(250,
40 + x * 40)
cb.Name = "RunTime" & CStr(cbCount)
cb.Text = "RunTime" & CStr(cbCount)
Me.Controls.Add(cb)
cbCount += 1
'add the click event and point to existing
click event
AddHandler cb.Click, AddressOf cbDesignTime_Click
Next
Catch
MsgBox("Please ensure you have entered a number of
controls to create in the exbox!")
tbButtonAmount.Select()
End Try
End Sub
Again CType is used to convert the amount entered in the textbox to an integer
and further on we convert the form level variable cbCount to a string for naming
of the buttons.
The key from an event point of view is the AddHandler method. This allows us
to dynamically apply the new control to an event handler.
Finally the whole thing is contained in a Try..Catch..End Try block in case no
proper number is entered (most likely error), a good example of the new error
trapping techniques in vb.net.
Happy Programming.