More 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:
-
This seems a little silly to even mention here, but some people don't now how to actually trigger events for which they've sculpted all that nifty jQuery co ...
-
What you need before we start:- Manufacturer and Model Name (can be found on the printer case)- IP Address (can usually be found on a label attached to the ...
-
So we all know about the cool little Quick Launch panel sitting on the left hand side of the Taskbar (just next to the Windows Start button) at the bottom o ...
-
Ugh, file copying on Vista is a rather uneven affair, sometimes files blip between folders at blistering pace, and other times you may as well go put the ke ...
-
While the new Microsoft Office Word 2007 has simply made things a whole lot easier for entry-level users as a whole, it can be more than a little frustratin ...