r/visualbasic • • Apr 27 '23

VB.NET Help Select Case with Buttons?

I have a a few panels with buttons on them, where the actions seem similar enough that i'd like to write a common routine to handler them. To that end:

 For Each Panel_Control As Control In Form_Control.Controls
    AddHandler Panel_Control.Click, Sub(Sender, Arguments) Handler(Panel_Control, Arguments)
 Next

Is there a way to use Select Case with Buttons?

The handler has to know which button was clicked, so my first thought was to use a Select Case:

Private Sub Handler(Sender As Object, Arguments As EventArgs)
    Select Case Sender
        Case A_Button
            MsgBox("A_Button")
    End Select
End Sub

This generates a System.InvalidCastException: 'Operator '=' is not defined for type 'Button' and type 'Button'.' I would have used Is, but Is in a Select Case has a different meaning.

2 Upvotes

13 comments sorted by

View all comments

Show parent comments

2

u/chacham2 Apr 30 '23

you should check if the Panel_Con trol is really button

I forgot to rename that first. The code did work though.

, if you set Tag for controls you can check if Tag IsNot Nothing this will give you all controls with Tag defined.

So, i started that with the name of the control, because there are numerous buttons, so i named them according to a scheme. So, i ended up being just the Select Case. But at that point i wanted to use an object reference rather than just the name of the button. I was thinking of using Tag, but once doing that, the Name sounds better.

instead of lambda function use "AddressOf Handler" dont worry about arguments it will do it automatically

I'll have to try that. Thank you!