Search code examples
vb.netloopscontrolsaddhandler

VB.NET AddHandler to each button control while looping through controls


I am trying to add mouseenter and mouseleave events to each button while I'm looping through the controls like:

For each control in me.controls
       With control
            If TypeName(control) = "Button" Then
                AddHandler control.MouseEnter, AddressOf control.DynamicButton_MouseEnter
                AddHandler control.MouseLeave, AddressOf control.DynamicButton_MouseLeave
            end if
next

And it says "MouseEnter is not an event of object". So I wonder how do I reference the dynamic button?


Solution

  • You can try fetching only the Buttons on the form.
    Should cause the control to be of the correct type for attaching a handler.

       Private Sub AddButtonEvents()
    
            For Each control In Me.Controls.OfType(Of Button)
                AddHandler control.MouseEnter, AddressOf DynamicButton_MouseEnter
                AddHandler control.MouseLeave, AddressOf DynamicButton_MouseLeave
            Next
    
        End Sub
    

    Or you can loop as you already are doing, and cast as follows

        Private Sub AddControlHandlers()
    
            For Each control In Me.Controls
    
                If TypeName(control) = "Button" Then
    
                    AddHandler DirectCast(control, Button).MouseEnter, AddressOf DynamicButton_MouseEnter
                    AddHandler DirectCast(control, Button).MouseLeave, AddressOf DynamicButton_MouseLeave
    
                End If
    
            Next
    
        End Sub