I have a groupbox containing a lot of Checkboxes - only Checkboxes.
Is there a simple/fast way to handle the same event coming from different controls?
I know I can write a single sub and let it handle all the Events, but it's really time-consuming to write.
Using Visual Studio 2012
If your time concern is about writing and managing a large Handles
clause, you can simply loop through the GroupBox
's Controls
collection upon construction of your UserControl
/Form
and wire up each event on each CheckBox
, like so:
Imports System.Linq
Public Sub New()
InitializeComponent()
For Each chkBox As CheckBox In yourGroupBoxVariable.Controls.OfType(Of CheckBox)()
AddHandler chkBox.CheckStateChanged, AddressOf YourCheckStateChangedHandlerMethod
Next
End Sub
Private Sub YourCheckStateChangedHandlerMethod(ByVal sender As Object, ByVal e As EventArgs)
' Your handler code for the checkboxes
End Sub
This leverages LINQ's OfType Enumerable extension to filter down all child controls of the GroupBox
to those of type CheckBox
.