设置CheckBox基于GroupBox的CheckBoxes进行检查

时间:2016-09-02 02:35:38

标签: vb.net winforms checkbox groupbox

早上好 我想问一些与复选框相关的内容 我需要一组复选框,它看起来像这样

enter image description here

我的问题是,每当我选中组Purchase Requisition中的任何复选框时,如何选中复选框Purchase Requisition,如果取消选中所有复选框,则取消选中复选框Purchase Requisition

我有这段代码,我将此代码放在Groupbox Purchase Requisition

中的所有复选框中
  Sub check_Purchase_Req()
        Dim oCtl As Control
        Dim iX As Integer

        For Each oCtl In GroupBox3.Controls
            If TypeName(oCtl) = "CheckBox" And oCtl.Enabled = True Then iX = iX + 1

            If iX > 0 Then
                CheckBox1.Checked = True

            ElseIf CheckBox19.Checked = False And CheckBox20.Checked = False And CheckBox21.Checked = False And CheckBox22.Checked = False And CheckBox23.Checked = False Then

                CheckBox1.Checked = False
                Exit For
            End If
        Next
    End Sub

但是这段代码不符合我的需要

任何帮助表示赞赏TYSM

2 个答案:

答案 0 :(得分:2)

使用linq执行此类任务可以简化生活:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    GroupBox1.Controls.OfType(Of CheckBox).ToList() _
             .ForEach(Sub(c) AddHandler c.CheckedChanged, AddressOf CheckChanged)
End Sub
Private Sub CheckChanged(sender As Object, e As EventArgs)
    CheckBox1.Checked = GroupBox1.Controls.OfType(Of CheckBox).Any(Function(c) c.Checked)
End Sub

在上面的代码中,我认为GroupBox1是正确的,CheckBox1是您要根据CheckBox的{​​{1}}控件检查或取消选中的GroupBox1

答案 1 :(得分:1)

此处,Checkbox1到Checkbox5是Purchase Requisition组框内复选框的假定名称。

chkPurchaseRequisition也是“购买请求”复选框的复选框

试试这个:

 Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles _
CheckBox1.CheckedChanged, CheckBox2.CheckedChanged, CheckBox3.CheckedChanged, CheckBox4.CheckedChanged, CheckBox5.CheckedChanged
    If sender.Checked = True Then
        chkPurchaseRequisition.Checked = True
    Else
        Dim AllUnchecked As Boolean = True
        For Each c As Control In grpboxPurchaseRequisition.Controls.OfType(Of CheckBox)()
            If DirectCast(c, CheckBox).Checked = True Then
                AllUnchecked = False
                Exit For
            End If
        Next
        If AllUnchecked = True Then
            chkPurchaseRequisition.Checked = False
        End If
    End If

End Sub