VB .Net: Programmatically add Event Handlers to Controls at Runtime Programming 10 SEP 2008

Dot NetMore than once I’ve found myself needing to add event handlers to controls (like labels for instance) that I am generating on the fly based on ever changing parameters like folder contents or something like that.

Now generating and adding on new controls at runtime is a pretty simple thing to do in Visual Basic .NET and luckily for us adding event handlers to these newly generated controls are a cinch as well.

Let’s illustrate what I’m saying with an example.

Dim newButton as Windows.Forms.Button
newButton = New Windows.Forms.Button
newButton.Name = “Button1”
newButton.Text = “Press Me”
newButton.Top = 20
newButton.Left = 40
Me.Controls.Add(newButton)

Now what we’ve done here is generate a button control and add it to the currently displayed form. However, clicking on this button is pretty pointless as it has not been assigned any job to do when clicked upon.

So to add on to the previous example, what we actually want to do is this:

Dim newButton as Windows.Forms.Button
newButton = New Windows.Forms.Button
newButton.Name = “Button1”
newButton.Text = “Press Me”
newButton.Top = 20
newButton.Left = 40
AddHandler newButton.Click, AddressOf ButtonClicked
Me.Controls.Add(newButton)

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

And it is as easy as that. By adding the ‘AddHandler’ statement to the new control and pointing it to the address of our defined function, clicking on our new button will result in a message box popping up and giving us some information as defined by our function.

Not that complicated, eh?

(You’ll note that another way of doing this (and perhaps a more correct way) is by defining the newly created control as a global variable outside of your generating code first, in other words:

Public WithEvents newButton As Windows.Forms.Button

However, you can get away with simply doing as I’ve demonstrated in the first example.)

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.