选中两个复选框时,禁用GroupBox中的其他复选框

时间:2017-02-25 10:31:39

标签: vb.net checkbox

 Private Sub AllBoxes_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged, CheckBox2.CheckedChanged, CheckBox3.CheckedChanged, CheckBox4.CheckedChanged, CheckBox5.CheckedChanged, CheckBox6.CheckedChanged

    Dim qty As Int16 = 0
    Dim cb As CheckBox


    For Each cb In GroupBox8.Controls.OfType(Of CheckBox)
        If cb.Checked Then
            qty += 1
        End If
    Next

    If qty = 2 Then

        For Each cb In GroupBox8.Controls.OfType(Of CheckBox)
            If Not cb.Checked Then
                cb.Enabled = False
            End If
        Next
    Else

        For Each cb In GroupBox8.Controls.OfType(Of CheckBox)
            cb.Enabled = True
        Next
    End If
End Sub
它只是不起作用。 groupbox的名称是groupbox8,它上面有6个复选框。我需要选择两个复选框。

1 个答案:

答案 0 :(得分:1)

您可以使用一点Linq

简化CheckedChanged事件处理程序
Private Sub AllBoxes_CheckedChanged(sender As Object, e As EventArgs)

    ' Get all checkboxes in the groupBox8
    Dim checks = groupBox8.Controls.OfType(Of CheckBox)()
    ' Count how many are checked
    Dim cnt = checks.Where(Function(x) x.Checked).Count()

    If cnt < 2 Then
        ' Enable all, avoid an if and don't care if already enabled
        For Each c In checks
            c.Enabled = True
        Next
    Else
        ' Disable all except the two checked...
        For Each k In checks.Where(Function(x)  Not x.Checked)
            k.Enabled = False
        Next
    End If
End Sub