VB.Net Can I manage all events from within the groupbox in an efficient way?
If your time is about writing and managing a big sentence Handles
, you can just skip the collection GroupBox
Controls
when building your UserControl
/ Form
and wire each event on each one CheckBox
, for example:
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 uses the LINQ OfType Enumerated Extension to filter out all child controls GroupBox
with respect to type CheckBox
.
source to share
Another possibility is to create a custom one GroupBox
, i.e. get from GroupBox
and expose the event yourself:
Public Class CheckboxGroup
Inherits GroupBox
Public Event CheckboxChanged(source As CheckBox, e As EventArgs)
Protected Overrides Sub OnControlAdded(e As ControlEventArgs)
' this method is called everytime a checkbox is added
If TypeOf e.Control Is CheckBox Then
Dim chk As CheckBox = DirectCast(e.Control, CheckBox)
AddHandler chk.CheckedChanged, AddressOf AllCheckedChange
End If
End Sub
Private Sub AllCheckedChange(source As Object, e As EventArgs)
If TypeOf source Is CheckBox Then
Dim chk As CheckBox = DirectCast(source, CheckBox)
RaiseEvent CheckboxChanged(chk, e)
End If
End Sub
End Class
Then you can attach to the event in Form
like:
Private Sub CheckboxChanged(source As CheckBox, e As EventArgs) Handles gb.CheckboxChanged
MsgBox(source.Text & " to " & source.Checked)
End Sub
Advantage: you can never miss adding an event handler to CheckBox
, even if it is dynamically created.
source to share