VB.Net Can I manage all events from within the groupbox in an efficient way?

I have a group box containing many checkboxes - only checkboxes.

Is there a simple / quick way to handle the same event from different controls?

I know that I can write one subset and let it handle all events, but this is very time consuming to write.

Using Visual Studio 2012

+3


source to share


2 answers


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

.

+1


source


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.

+1


source







All Articles