Monday, June 11, 2007

Programmatically Add Event Handlers to Controls At Runtime

If you have read my previous blogs, you'll see that I have discussed about how to add and remove controls at run time. Some controls created at runtime are pretty much useless if they have no event handlers attached to them.

What are event handlers? Think of event handlers as actions that are bound to controls. What action(s) would you want to carry out when certain things happen (ie: like a button is clicked, doubleclicked…)?

Let take a look at the following lines of code:

Dim newButton as Windows.Forms.Button
Dim i As Integer
For i = 1 To 5
newButton = New Windows.Forms.Button
newButton.Name = "btnButton" & i
newButton.Text = "Button " & i
newButton.Top = 20 + i * 30
newButton.Left = 40
Me.Controls.Add(newButton)
Next

The code block above will add 5 buttons to the form at runtime. But when you click on the buttons, nothing happen. Why? This is because at this time, there are no event handlers attached to the buttons.

Let make some modifications:

Public WithEvents newButton As Windows.Forms.Button
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim i As Integer
For i = 1 To 5
newButton = New Windows.Forms.Button
newButton.Name = "btnButton" & i
newButton.Text = "Button " & i
newButton.Top = 20 + i * 30
newButton.Left = 40
AddHandler newButton.Click, AddressOf ButtonClicked
Me.Controls.Add(newButton)
Next
End Sub

Private Sub ButtonClicked(ByVal sender As Object, ByVal e As EventArgs)
MsgBox("You clicked: " & sender.name & vbCrLf & "Button name: " & sender.Text)
End Sub

Here the newButton has been redefined as a control with events and the AddHandler call attached the method ButtonClicked to the Click event of the control. Note that the control is declared as a global variable. You can’t declare a control with events as a local variable. The address of ButtonClick method is then bound or attached to newButton’s click event. Any time the button is clicked, ButtonClicked method will run and a message box will be displayed.

As you can see, it's pretty straight forward to add, remove and attached events to controls that are created on the fly. This blog only scratches the surface of these issues. You can further your study from these links:

Delegates and the AddressOf Operator
Events and Event Handlers

Download sample code: EventHandlers.zip

1 comment:

Anonymous said...

Good Day!!! brian-dao.blogspot.com is one of the best innovative websites of its kind. I enjoy reading it every day. Keep it that way.