Get Selected CheckBoxes from container





0/5 (0 vote)
Returns all checked Checkbox controls in a Windows Form container
The code presented gets all checked
CheckBox
controls within a single container such as a Group Box or Panel. In short, the code has been placed into an extension method so that your business logic is cleared of unnecessary code as to determining which CheckBox
controls are checked.
Usage
Declare a List(Of CheckBox) variable which will return all Checkbox
es which are checked if the extension method returns True
indicating that there are one or more CheckBox
es checked. If the method returns False
, there are no CheckBox
es checked in the container.
Example where we are checking CheckBox
es contained in GroupBox1
:
Dim List As New List(Of CheckBox)
If GroupBox1.CheckBoxesChecked(List) Then
For Each Item In List
Console.WriteLine(Item.Name)
Next
Else
Console.WriteLine("Nothing checked")
End If
Extension method
<System.Diagnostics.DebuggerStepThrough()> _ <System.Runtime.CompilerServices.Extension()> _ Public Function CheckBoxesChecked( _ ByVal container As Control, _ ByRef CheckBoxes As List(Of CheckBox)) As Boolean Dim Result As Boolean = False Dim CheckBoxCollection = From Control In container.Controls Where TypeOf Control Is CheckBox Select C = DirectCast(Control, CheckBox) If Not CheckBoxCollection Is Nothing Then Dim CheckedList = (From Item In CheckBoxCollection Where Item.Checked).ToList CheckBoxes = CheckedList Result = CheckedList.Count > 0 End If Return Result End Function