Showing posts with label Event handlers. Show all posts
Showing posts with label Event handlers. Show all posts

Tuesday, February 9, 2010

Dynamic button creation

Dynamic button creation in VB.NET with click events

It is simple to create a button runtime. But it is one more step to define a respective event handler for the events for the control.





Load buttons

Private Sub loadButtons()
Dim intNoOfTextBox As Integer = 10
For intC As Integer = 0 To intNoOfTextBox - 1
Dim objButton As Button
objButton = New Button
objButton.Size = New Size(200, 25)
objButton.Location = New Point(5, intC * 25)
objButton.Text = " My Runtime Dynamic Button " & (intC + 1).ToString
AddHandler objButton.Click, AddressOf ButtonClick
Me.Controls.Add(objButton)
Next
End Sub

Event handler for button click

Private Sub ButtonClick(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim objTempButton As Button = CType(sender, Button)
Dim strButtonText As String = ""
strButtonText = objTempButton.Text.Trim
MessageBox.Show(strButtonText)
End Sub