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

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

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.

  • MichaelBoy

    very useful for a beginner! thank you so much.

  • Mavros Katramis

    I have this sub where i get header values and item data from a listview control. Then I create new controls into TableLayoutPanel. I use this method because every time list view have different columns.count and rows.count. Everything works fine.

    BUT in my new form ( frmFieldsData ) i want to handle the controls I just created. The problem is when I add handler. I get an error saying ( Name ‘txtBox_TextChanged’ is not declared. ).

    What am i doing wrong?

    Private Sub lstTableFields_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lstTableFields.MouseDoubleClick
            With frmFieldsData.tblLayoutFieldData
                For i = 0 To lstTableFields.Columns.Count – 1
                    Dim style As New RowStyle(SizeType.Absolute, 30)
                    Dim lblLabel As New Label
                    Dim chkBox As New CheckBox
                    Dim txtBox As New TextBox
                    txtBox = New TextBox

                    txtBox.Name = “txtData” & i.ToString
                    txtBox.Size = New Size(300, 40)
                    txtBox.Text = lstTableFields.SelectedItems(0).SubItems(i).Text.ToString
                    AddHandler txtBox.TextChanged, AddressOf txtBox_TextChanged ‘ERROR

                    lblLabel.Text = lstTableFields.Columns(i).Text
                    lblLabel.Name = “lblField” & i.ToString

                    chkBox.Name = “chkBox” & i.ToString

                    .Controls.Add(lblLabel, 0, i + 1)
                    .Controls.Add(txtBox, 1, i + 1)
                    .Controls.Add(chkBox, 2, i + 1)
            End With

        End Sub

    Check Images Below

  • vishal

    thank you thnk u thnk u sooooo much……i m really searching this method last 1 month….thnk you a lot….