类似这样的逻辑如何工作?假设我有4个组合框和2个列表框。任何操作都需要第一个组合框。通过执行类似If Not ComboBox.SelectedIndex = -1 Then
然后,ComboBox 2-4是可选的,但必须考虑在内。进行多个嵌套的If检查会很麻烦,那么有没有更简单,更容易的解决方案?我将附上截图以显示我的意思
我不想做类似的事情:
If Not RequiredFruit.SelectedIndex = -1 Then
If Not Combo1.SelectedIndex = -1 Then
If Not Combo2.SelectedIndex = -1 Then
有更好的方法吗?
答案 0 :(得分:1)
您可以通过许多不同的方式来执行此操作。如果您不喜欢嵌套If
AndAlso
OrElse
,这是一种对每个选择选项使用小Functions
的方法。
Private Function SelectionCombo2() As String
If Not ComboBox2.SelectedIndex = -1 Then Return String.Format(", {0}", ComboBox2.SelectedItem)
Return String.Empty
End Function
Private Function SelectionCombo3() As String
If ComboBox3.SelectedIndex = -1 Then Return String.Format(", {0}", ComboBox3.SelectedItem)
Return String.Empty
End Function
Private Function SelectionCombo4() As String
If ComboBox4.SelectedIndex = -1 Then Return String.Format(", {0}", ComboBox4.SelectedItem)
Return String.Empty
End Function
Private Function SelectionList1() As String
If ListBox1.SelectedIndex = -1 Then Return String.Format(", {0}", ListBox1.SelectedItem)
Return String.Empty
End Function
控件名称需要更改才能更合适。
然后在您的Button
中单击仅测试第一个ComboBox
并显示结果。每个Function
都会照顾显示的内容。如果您喜欢这种方法,也可以将这些单独的Functions
压缩为一个。
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If Not ComboBox1.SelectedIndex = -1 Then
MessageBox.Show(String.Format("You have selected {0}{1}{2}{3}{4}", ComboBox1.SelectedItem, SelectionCombo2, SelectionCombo3, SelectionCombo4, SelectionList1))
Else
MessageBox.Show("You have selected nothing")
End If
End Sub
要使其更紧凑,请参见以下内容:
仅将一个Function
用于ComboBoxes
的示例:
Private Function Selection(Combo As ComboBox) As String
If Not Combo.SelectedIndex = -1 Then Return String.Format(", {0}", Combo.SelectedItem)
Return String.Empty
End Function
Button
显示将需要稍作更改:
MessageBox.Show(String.Format("You have selected {0}{1}{2}{3}{4}", ComboBox1.SelectedItem, Selection(ComboBox2), Selection(ComboBox3), Selection(ComboBox4), SelectionList1))