我设法使搜索功能正常工作,但它很粗:(
代码:
If dropdown_sV.Value = "N" Then
If WhereParts > 0 Then
WhereClause = WhereClause & " AND"
End If
WhereClause = WhereClause & " [sV] = 'N'"
WhereParts = WhereParts + 1
End If
If dropdown_sV.Value = "G" Then
If WhereParts > 0 Then
WhereClause = WhereClause & " AND"
End If
WhereClause = WhereClause & " [sV] = 'G'"
WhereParts = WhereParts + 1
End If
我能让这段代码更有效率吗,因为我有很多选择下拉框,有以下选项:n,g,o,a,r,u
维护我的应用程序将是一场噩梦。
最佳答案
您可以使用:
If dropdown_sV.SelectedIndex > -1 Then
If WhereClause.Length > 0 Then
WhereClause = WhereClause & " AND"
End If
WhereClause = WhereClause & " [sV] = " & dropdown_sV.Value
End If
但您确实应该考虑将查询参数化(如下所示):
If dropdown_sV.SelectedIndex > -1 Then
If WhereClause.Length > 0 Then
WhereClause = WhereClause & " AND"
End If
WhereClause = WhereClause & " [sV] = @sV"
End If
生成
WHERE
子句后,只需将参数与值关联即可:Dim cmd As SqlCommand = New SqlCommand(queryString, connectionString)
cmd.Parameters.Add("sV", SqlDbType.VarChar, 50).Value = dropdown_sV.Value