我有一个 For Each 语句,我希望能够从在我的组合框中选择某个选项的开头开始。这可能吗?
For Each cbo As ComboBox In s_combos
For Each cov As String In s_coverage
If combo.Name = cbo.Name And combo.SelectedIndex = 0 Then
If txtNewMoney.Text <> "" And b_isSmoker = False Then
CalculateRunningTotal(False, cov, , CKeyValuePair.GetComboBoxSelectedKey(s_applicants(counter), True))
ElseIf txtNewMoney.Text <> "" And b_isSmoker = True Then
CalculateRunningTotal(True, cov, , CKeyValuePair.GetComboBoxSelectedKey(s_applicants(counter), True))
End If
counter += 1
Exit For
End If
Next
If combo.Name = cbo.Name And combo.SelectedIndex = 1 Then
'If this option is selected, start over in For Each
counter -= 1
Dim dec As frmDeclined = New frmDeclined(DirectCast(sender, Control).Name, Me)
dec.ShowDialog()
End If
Next
你可以改用一个普通的 for 循环,并将迭代器设置回它的初始值。不过,最好对其进行重组以提高效率,如果选择了该选项,第一次循环有什么意义吗?
从循环内部修改For
循环的索引通常被认为是不礼貌的。
一种社会可接受的方法是使用While
循环,并在循环中递增或重置自变量。
如果您肯定想使用For
...Each
循环中,您可以在其外部放置一个While
循环以进行迭代以有效地重置For
......Each
循环。在我能想到的几乎所有情况下,这都是不必要的复杂,我通常不推荐它。
您可以创建一个标签并转到它:
GoHere:
For Each cbo As ComboBox In s_combos
For Each cov As String In s_coverage
If combo.Name = cbo.Name And combo.SelectedIndex = 0 Then
If txtNewMoney.Text <> "" And b_isSmoker = False Then
CalculateRunningTotal(False, cov, , CKeyValuePair.GetComboBoxSelectedKey(s_applicants(counter), True))
ElseIf txtNewMoney.Text <> "" And b_isSmoker = True Then
CalculateRunningTotal(True, cov, , CKeyValuePair.GetComboBoxSelectedKey(s_applicants(counter), True))
End If
counter += 1
Exit For
End If
Next
If combo.Name = cbo.Name And combo.SelectedIndex = 1 Then
'If this option is selected, start over in For Each
counter -= 1
Dim dec As frmDeclined = New frmDeclined(DirectCast(sender, Control).Name, Me)
dec.ShowDialog()
Goto GoHere
End If
Next