Click here to Skip to main content
15,881,671 members
Articles / Programming Languages / Visual Basic
Tip/Trick

Get Selected CheckBoxes from container

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
24 Jan 2011CPOL 11.3K   3  
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)


Written By
Instructor / Trainer
United States United States
Microsoft MVP, Uses Microsoft Visual Studio ecosystem building web and desktop solutions

Comments and Discussions

 
-- There are no messages in this forum --