Can I loop through controls in a group and find out which button is clicked?

emaduddeen

Well-known member
Joined
May 5, 2010
Messages
171
Location
Lowell, MA & Occasionally Indonesia
Programming Experience
Beginner
Hi Everyone,

I have a form with many buttons on it and I would like to loop through all the controls in a group control and find out which button is clicked.

Is it possible to do this?

I plan to use the click event of the button and I know it's easy to create a click event procedure for all of the buttons but would like to avoid that.

The group control is called GroupFilterButtons.

Thanks.

Truly,
Emad
 

Attachments

  • form with filter.jpg
    form with filter.jpg
    118.3 KB · Views: 27
You can use addhandler to accomplish this

VB.NET:
    Private Sub ButtonClick(ByVal sender As System.Object, ByVal e As System.EventArgs)
        MessageBox.Show("you clicked: " & CType(sender, Button).Text)
    End Sub


     ' please notice in what event we add the handlers
     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        For Each ctrl As Control In GroupFilterButtons.Controls
            If TypeOf (ctrl) Is Button Then
                AddHandler ctrl.Click, AddressOf ButtonClick
            End If
        Next
    End Sub
 
I plan to use the click event of the button and I know it's easy to create a click event procedure for all of the buttons but would like to avoid that.
I don't think you realize how easy it actually is. You can select all controls in Designer and in Events view of Properties window select the single handler method if it exist, or type a name to have one generated. Designer then adds all the Handles for you.

You probably also needed to know what 'sender' means and how to handle it, which kulroms sample showed you.
 
Hi kulroms,

Works great! :)

I had to change it a bit since I'm using the PureComponents buttons.

VB.NET:
    Private Sub ButtonClick(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim strButtonClicked As String = CType(sender, PureComponents.EntrySet.Controls.Button).Text

        If strButtonClicked = "All" Then
            SetDataViewFilter("")
        Else
            SetDataViewFilter(strButtonClicked)
        End If
    End Sub

Hi JohnH,

Thanks for the "designer" technique. I tried it and see it added the buttons in the "Handles" area.

Truly,
Emad
 
Back
Top