Marcus Eagle
Marcus Eagle

Reputation: 95

VB - Unchecking Check Boxes in a Group Box

Currently I have 5 group boxes all filled with checkboxes, when I want to unselect all of them (for a 'clear selection' button), I use this code that I found on a forum:

For Each CheckBox In grpbox_Hiragana
        CheckBox.checked = "false"

Firstly, I'm sure if this is the correct way to unselect the checkboxes, secondly the "grpbox_Hiragana" groupbox returns the following error:

Expression is of type 'System.Windows.Forms.GroupBox', which is not a collection type

If anyone could confirm this is the correct way of doing this/ help fix the error by telling me why the groupbox won't be accepted that would be great.

Upvotes: 1

Views: 10502

Answers (2)

OSKM
OSKM

Reputation: 728

A alternative with less lines of code is:

 For Each ChkBox As CheckBox In GroupBox1.Controls
    ChkBox.Checked = False
 Next

Incidentally your code would have worked if you added .controls, the As CheckBox just enables the intellisense (and also ensures it is only Checkbox's that are processed) .

Upvotes: 0

Al-3sli
Al-3sli

Reputation: 2181

if you have all check box on one group box use this code :

    Dim ChkBox As CheckBox = Nothing
    ' to unchecked all 
    For Each xObject As Object In Me.GroupBox1.Controls
        If TypeOf xObject Is CheckBox Then
            ChkBox = xObject
            ChkBox.Checked = False
        End If
    Next

   ' to checked all 
    For Each xObject As Object In Me.GroupBox1.Controls
        If TypeOf xObject Is CheckBox Then
            ChkBox = xObject
            ChkBox.Checked = True
        End If
    Next

Or you can use CheckedListBox Control.

Upvotes: 2

Related Questions