Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / VB

Get Selected CheckBoxes from container

0.00/5 (No votes)
24 Jan 2011CPOL 11.5K  
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:
VB
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)