Dynamic Control Creation ( Event Handlers )

Begginnerdev 0 Tallied Votes 511 Views Share

After seeing quite a few posts today asking about event handlers for dynamicly created controls, I have decided to give a little example for reference.

Note that you should check Microsoft's Documentation ( or research from web ) of any control if you are struggling

'When you are creating controls dynamicly - and you want to create handlers for them - you can do so by including the WithEvents keyword

    'If you want the control to be accessed project wide - declare it as Friend
    Friend WithEvents TextBox1 As New TextBox
    'If you only want the control to be access locally - Declare it as Dim or Private
    Dim WithEvents Label1 As New Label
    Private WithEvents Label2 As New Label

    Dim txtNoHandlers As New TextBox

    'If you are having trouble figuring out which Event handler to add to your event - pass in a random one and intellisence will tell you the correct one.

    'You can now directly reference the controls.
    Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
        'Do Work
    End Sub

    Private Sub Label1_TextChanged(sender As Object, e As EventArgs) Handles Label1.TextChanged
        'Do work
    End Sub


    Private Sub Me_Load(sender As Object, e As EventArgs) Handles Me.Load
        'You can also add the handlers manually by calling the AddHandler statement
        AddHandler txtNoHandlers.TextChanged, AddressOf New_Handler
    End Sub


    Private Sub New_Handler(sender As Object, e As EventArgs)
        'Do work
    End Sub