Connor Albright
Connor Albright

Reputation: 743

Working with the events of various controls

I want to use the following snippit.

    For Each x As Control In Me.Controls
        If TypeOf x Is CustomControl Then
            SomeAction( x.CustomEventofCustomControl)
        End If
    Next

The problem here is that not all controls have event CustomEventofCustomControl, so the complier shrieks. How do I get around this.

ps: Any ideas for a better title?

Upvotes: 0

Views: 91

Answers (2)

Connor Albright
Connor Albright

Reputation: 743

What solved the problem for me:

 For Each x As Control In Me.Controls
        If TypeOf x Is CustomControl Then
            SomeAction( CType(x, CustomControl).CustomEventofCustomControl)
        End If
    Next

Upvotes: 0

Matías Fidemraizer
Matías Fidemraizer

Reputation: 64943

A good idea would be use some marker interface like IHasWhateverEvent (tell me which one and I'll compose a better name, of course!). That interface has no members, since it's a marker one.

You make any of your custom controls having that event implement this blank interface, then you do that:

For Each x As Control In Me.Controls
        If x Is IHasWhateverEvent Then
            SomeAction(((IHasWhateverEvent)x).CustomEventofCustomControl)
        End If
Next

Or if you can, just add an event in your interface so when you cast some control to IHasWhateverEvent, you'll have access to the event itself.

Upvotes: 1

Related Questions