65.9K
CodeProject is changing. Read more.
Home

Get Selected CheckBoxes from container

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Jan 24, 2011

CPOL
viewsIcon

11464

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 Checkboxes which are checked if the extension method returns True indicating that there are one or more CheckBoxes checked. If the method returns False, there are no CheckBoxes checked in the container. Example where we are checking CheckBoxes 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
Get Selected CheckBoxes from container - CodeProject