bernzkie
bernzkie

Reputation: 1269

Count and get all the value of checked checkboxes in VB.NET

lets say i have a form, and under my form i have a panel, and under panel i have a groupbox, and under the groupbox i have another panel, and under of this panel i have a multiple checkboxes, now, how can i count how many checkboxes are checked and how can i get the value of checked checkboxes and put it in arraylist. i have a code but doesnt work.

my code:

        Dim list As New ArrayList
        Dim count As Integer
        count = 0
        If TypeOf element Is CheckBox Then

         If cb.Checked Then
            list.Add(cb.Text)
        'End If
        Else
            For Each childElement In element.Controls
               count += 1
            Next
        End If
        MsgBox(count)
        MsgBox(list)

thank you very much! any help will appreciate. sorry for y bad English.

Upvotes: 0

Views: 10406

Answers (3)

Polar
Polar

Reputation: 3537

you can do it using recursive. try this.

        Private Sub getcheckme(ByVal element As Control)
        Dim count As Integer
        count = 0
        If TypeOf element Is CheckBox Then
            If DirectCast(element, CheckBox).Checked = True Then
                count += 1 'this will count the checked checkboxes
                list.Add(element.Text) ' this will add the value of checkboxes into arraylist
            End If
        Else
            For Each childElement In element.Controls
                Me.getcheckme(childElement)
            Next
        End If
        End Sub

just call it using: Me.getcheckme(Me)

Upvotes: 0

Blackwood
Blackwood

Reputation: 4534

Loop through all the controls in the inner panel and check to see if they are CheckBoxes. If they are, and they are checked, increment the count and add the text to the list. I would use a generic List(Of String) rather than an ArrayList.

Dim count As Integer 
Dim myList As New List(Of String)
For Each cb As CheckBox In panel1.Controls.OfType(Of CheckBox)
    If cb.Checked Then
        count += 1
        myList.Add(cb.Text)
    End If
Next
MessageBox.Show(count.ToString)
MessageBox.Show(String.Join(", ", myList))

[Edit] Code was simplified, as suggested by Plutonix, to use Controls.OfType(Of CheckBox) to loop through only the controls that are of type CheckBox,

Upvotes: 1

bbakiu
bbakiu

Reputation: 281

Dim chk As CheckBox
For Each c As Control In thePanel.Controls

    if Typeof c is CheckBox then
     count += 1 // to count check boxes
        chk  =  Ctype(c, Checkbox)
        if chk.Checked Then
            list.Add(chk.Text) // to add the text of checkbox to array
        End If
    End If
Next

Upvotes: 0

Related Questions