【问题标题】:VB - Running an if statement if only a certain number of checkboxes are checked?VB - 如果仅选中一定数量的复选框,则运行 if 语句?
【发布时间】:2015-10-15 14:08:55
【问题描述】:

我正在为我刚开始的 VB 课程创建一个披萨订购系统。我可以为披萨编写一个浇头,但是当我尝试添加一个以上的浇头时,我得到的项目有两个浇头,但还有另外两个只有一个浇头的披萨。如果在分组框中只选中了一定数量的复选框,有没有办法运行 if 语句?

Private Sub AddItems()

   'Declare Topping Variables 
    Dim topping1 As String = "Pepperoni"
    Dim topping2 As String = "Bacon"
    Dim topping3 As String = "Ham"

    'Declare Size Variables 
    Dim strPersonal As String = "Persoanl"
    Dim strSmall As String = "Small"
    Dim strMedium As String = "Medium"
    Dim strLarge As String = "Large"
    Dim strExLarge As String = "Extra Large"

    'Personal Single Item
    If radPersonal.Checked = True And chkPepperoni.Checked = True Then
        CheckedListBox1.Items.Add(strPersonal & " with " & topping1)
    End If
    If radPersonal.Checked = True And chkBacon.Checked = True Then
        CheckedListBox1.Items.Add(strPersonal & " with " & topping2)
    End If
    If radPersonal.Checked = True And chkHam.Checked = True Then
        CheckedListBox1.Items.Add(strPersonal & " with " & topping3)
    End If

    'Personal Two Items
    If radPersonal.Checked = True And chkPepperoni.Checked = True And chkBacon.Checked = True Then
        CheckedListBox1.Items.Add(strPersonal & " with " & topping1 & " and " & topping2)
    End If
    If radPersonal.Checked = True And chkBacon.Checked = True And chkHam.Checked = True Then
        CheckedListBox1.Items.Add(strPersonal & " with " & topping2 & " and " & topping3)
    End If
    If radPersonal.Checked = True And chkHam.Checked = True And chkPepperoni.Checked = True Then
        CheckedListBox1.Items.Add(strPersonal & " with " & topping3 & " and " & topping1)
    End If
End Sub

http://i.stack.imgur.com/VafZe.png

【问题讨论】:

    标签: vb.net checkbox groupbox


    【解决方案1】:

    首先,您不应该测试radPersonal.Checked 六次。你应该只测试一次,然后嵌套其余的。

    其次,您不应该先单独测试chkPepperoni.Checked,然后再组合测试。如果你这样做,如果它被组合检查,它将匹配两个测试。您应该首先测试组合,然后仅在组合不匹配时单独测试它。以下是我可能倾向于这样做的方式:

    If radPersonal.Checked Then
        If chkPepperoni.Checked Then
            If chkBacon.Checked Then
                'pepperoni and bacon
            ElseIf chkHam.Checked Then
                'pepperoni and ham
            Else
                'pepperoni only
            End If
        ElseIf chkBacon.Checked Then
            If chkHam.Checked Then
                'bacon and ham
            Else
                'bacon only
            End If
        ElseIf chkHam.Checked Then
            'ham only
        End If
    End If
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2013-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-08
      相关资源
      最近更新 更多