我需要从访问数据库中过滤大量数据。我正在构建一个程序来实现这一目标,但是在过滤器中使用多个条件时遇到了问题。例如,以下是使用给定月份和颜色进行选择的测试代码:
If RadioButton1.Checked Then
If RadioButton4.Checked Then
Me.BindingSource.Filter = "[January] = 'True' AND [Red] = 'True'"
ElseIf RadioButton5.Checked Then
Me.BindingSource.Filter = "[January] = 'True' AND [Yellow] = 'True'"
ElseIf RadioButton6.Checked Then
Me.BindingSource.Filter = "[January] = 'True' AND [Blue] = 'True'"
Else Me.BindingSource.Filter = "[January] = 'True'"
End If
ElseIf RadioButton2.Checked Then
If RadioButton4.Checked Then
Me.BindingSource.Filter = "[February] = 'True' AND [Red] = 'True'"
ElseIf RadioButton5.Checked Then
Me.BindingSource.Filter = "[February] = 'True' AND [Yellow] = 'True'"
ElseIf RadioButton6.Checked Then
Me.BindingSource.Filter = "[February] = 'True' AND [Blue] = 'True'"
Else Me.BindingSource.Filter = "[February] = 'True'"
End If
ElseIf RadioButton3.Checked Then
If RadioButton4.Checked Then
Me.BindingSource.Filter = "[March] = 'True' AND [Red] = 'True'"
ElseIf RadioButton5.Checked Then
Me.BindingSource.Filter = "[March] = 'True' AND [Yellow] = 'True'"
ElseIf RadioButton6.Checked Then
Me.BindingSource.Filter = "[March] = 'True' AND [Blue] = 'True'"
Else Me.BindingSource.Filter = "[March] = 'True'"
End If
End If
现在这是一个甚至三个月和颜色的大量代码。必须有更好的方法来做到这一点,对吧?由于表中的字段数量很多,我需要对其进行排序,这样做需要花费数年的时间。
答案 0 :(得分:0)
对于这么简单的代码,您可以使用Switch语句:
Dim sMonth As String
Dim sColor As String
sMonth = Switch(RadioButton1.Checked, "[January]", RadioButton2.Checked, "[February]", RadioButton3.Checked, "[March]")
sColor = Switch(RadioButton4.Checked, "[Red]", RadioButton5.Checked, "[Yellow]", RadioButton6.Checked, "[Blue]")
Me.BindingSource.Filter = sMonth & " = 'True' AND " & sColor & " = 'True'"
这仍然是可读的。您也可以使用Select Case语句,诀窍是将其分为两部分。
答案 1 :(得分:0)
您需要从颜色按钮中拆分月份按钮,方法是:
Dim wc as string
'months
if RadioButto1.Checked then wc = "January = true"
elseif radiobutton2.checked then wc = "February = true"
. . . .
end if
'colours
If radiobutton4.checked then
wc &= " AND Red = true"
elseif radiobutton5.checked then
wc &= " AND Yellow = true"
. . . . .
end if
me.bindingsource.filter = wc