你好stackoverflow的人,我创建了一个groupBox1,其中包含39个可以单独检查的复选框,我创建了一个gropuBox2,其中包含一个名为" Check All"的单一复选框,我想要的是当"全部检查"选中复选框,将选中所有39个复选框,并且选中"全部检查"未经检查所有39个复选框也将被取消选中,有人可以帮忙吗?非常感谢你。
答案 0 :(得分:4)
如果所有控件都在表单中(不在groupbox / pannel中),您可以使用以下代码
Dim chk As CheckBox
If checkAll.Checked = True Then
For Each ctrl As Control In Me.Controls
If TypeOf ctrl Is CheckBox Then
chk = DirectCast(ctrl, CheckBox)
chk.Checked = True
End If
Next
End If
根据编辑和评论进行更新:
如果您想在Groupbox1
内找到控件,则表示您可以执行以下操作
''' <summary>
''' sets CheckBox.Checked inside a container
''' </summary>
''' <param name="parentControl">the container</param>
''' <param name="chkState">ture or false</param>
''' <remarks>use: checkControls(GroupBox1, True)</remarks>
Public Sub checkControls(ByVal parentControl As Control, chkState As Boolean) '<----Pass the parent control where the checkBoxes belongs
Dim chk As CheckBox = Nothing
For Each ctrl As Control In parentControl.Controls '<-----Change from the above code
If TypeOf ctrl Is CheckBox Then
DirectCast(ctrl, CheckBox).Checked = chkState
End If
Next
End Sub
要检查将该功能称为
checkControls(GroupBox1, True)'<----Since your checkboxes are inside the groupBox1
取消选中将该功能调用为
checkControls(GroupBox1, False)'<----Since your checkboxes are inside the groupBox1
答案 1 :(得分:0)
假设表单上有仅 40个复选框,那么这将起作用
Dim ctrl As Control = Me.GetNextControl(Me, True)
Do Until ctrl Is Nothing
If TypeOf ctrl Is CheckBox Then
DirectCast(ctrl, CheckBox).Checked = True
End If
ctrl = Me.GetNextControl(ctrl, True)
Loop
如果有超过40个复选框,请查看Neethu Soman的解决方案。
答案 2 :(得分:0)
以下 I 将如何做到这一点。使用Enumerable.OfType<T>按类型过滤控件,然后使用Array.ForEach<T>迭代结果。
Private Sub CheckBoxAll_CheckedChanged(sender As Object, e As EventArgs) Handles CheckAll.CheckedChanged
Array.ForEach(Me.GroupBox1.Controls.OfType(Of CheckBox).ToArray(), Sub(box As CheckBox) box.Checked = Me.CheckAll.Checked)
End Sub
答案 3 :(得分:0)
我已经尝试过以下代码并且适用于我,但Bjørn-RogerKringsjå代码效果更好:
Private Sub cbxAll_CheckedChanged(sender As Object, e As System.EventArgs) Handles cbxAll.CheckedChanged
If cbxAll.Checked = True Then
cbx01.Checked = True
cbx02.Checked = True
' 3 .. 38
cbx39.Checked = True
Else
cbx01.Checked = False
cbx02.Checked = False
' 3 .. 38
cbx39.Checked = False
End If
End Sub