VB .Net: Programmatically add Event Handlers to Controls at Runtime

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.)

You might also enjoy:

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in Technology & Code. Bookmark the permalink.
    blog comments powered by Disqus