用户选择比萨饼,大小等,并将比萨饼添加到篮子中(列表视图)。表单清除但用户可以再次单击添加按钮,这会将不需要的行添加到列表视图中。我已经尝试实现一个for循环来检查是否在添加新记录之前选中了复选框。结果,想要的记录添加到列表视图,但消息弹出x次。单击按钮时没有选中复选框也会出现此重复消息框。请帮忙吗?
'Add Pizza to Listview
Private Sub btnAddPizza_Click(sender As Object, e As EventArgs) Handles btnAddPizza.Click
Dim itemname As String
Dim price As Decimal
Dim qty As Integer
grandtotal = 0
'Add to list view
For Each rb1 In {rb01, rb02, rb03, rb04, rb05, rb06, rb07, rb08, rb09, rb10, rb11, rb12, rb13, rb14, rb15}
If rb1.Checked = True Then
itemname = GetCheckedItem()
price = CDec(pizzacost)
qty = 1
ListView1.Items.Add(New ListViewItem({itemname, qty, price}))
ElseIf rb1.Checked = False Then
MsgBox("No pizza is selected", MsgBoxStyle.Information)
End If
Next
'recalculate grandtotal (bottom of listview)
For Each x As ListViewItem In ListView1.Items
grandtotal += CDec(x.SubItems(2).Text)
Next
lblGrandTotal.Text = "£ " & grandtotal
'Discard Pizza selection
For Each rb In {rb01, rb02, rb03, rb04, rb05, rb06, rb07, rb08, rb09, rb10, rb11, rb12, rb13, rb14, rb15}
rb.Checked = False
Next
For Each rb In {rbSmall, rbMedium, rbLarge, rbSuper}
rb.Checked = False
Next
For Each rb In {rbDeep, rbThin, rbStuffed}
rb.Checked = False
Next
lblTotalPizza.Text = ""
itemname = ""
price = 0
End Sub
答案 0 :(得分:1)
目前还不清楚你要做的是什么,但我认为你的问题在于你只想让你的for循环中的代码执行一次。换句话说,而不是:
For Each rb In radioButtons
If rb.Checked Then ' This happens once per radio button
' Add item
Else
' Show Error
End If
Next
你想做这样的事情:
Dim found As Boolean
For Each rb In radioButtons
If rb.Checked Then ' This happens once per radio button
found = True
End If
Next
If found Then ' This happens once after the loop is done
' Add item
Else
' Show Error
End If
然而,LINQ通过它的Any
扩展方法使这样的事情更容易:
If radioButtons.Any(Function(rb) rb.Checked) Then
' Add item
Else
' Show Error
End If