VB - Unchecking Check Boxes in a Group Box

99封情书 提交于 2019-12-13 00:28:48

问题


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.


回答1:


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.




回答2:


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) .



来源:https://stackoverflow.com/questions/21060917/vb-unchecking-check-boxes-in-a-group-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!