0

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?

Eduards
  • 68
  • 2
  • 20

1 Answers1

1

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
Andrew Mortimer
  • 2,380
  • 7
  • 31
  • 33
  • I understand the answer, however it's not really suitable for me because I am looping through all controls and doing different things to different types of controls. That's why I have the IF statement like ``If TypeName(control) = "Button" Then`` so that I can deduce teh following code to apply to buttons, but I also have different things for ComboBoxes liek ``Elseif TypeName(control) = "ComboBox" then`` – Eduards Jan 25 '23 at 08:21
  • The code in the answer returns the same error where it says that Mouseenter is not an event of object – Eduards Jan 25 '23 at 08:36
  • 1
    Your addressof should refer to "DynamicButton_MouseEnter" and not "control.DynamicButton_MouseEnter", as DynamicButton_MouseEnter is your method and not an event on the control. – Andrew Mortimer Jan 25 '23 at 09:14