我有一个简单的数据库,我试图让它可以用多个标准进行搜索。我不知道的是如何让datagridview一起使用这些不同的标准进行过滤。我用if else语句知道我非常混乱。如果我使用组合框进行过滤,它将忽略我的所有其他标准。这是我的基本代码:
if (StartDate < EndDate)
{
employeeSuggestionsBindingSource.Filter = string.Format("[Suggestion Date] >= #{0:M/dd/yyyy}# AND [Suggestion Date] <= #{1:M/dd/yyyy}#", StartDate, EndDate);
}
else if (string.IsNullOrEmpty(SearchEmp) == false)
{
employeeSuggestionsBindingSource.Filter = string.Format("Employee like '%{0}%'", SearchEmp.Trim().Replace("'", "''"));
}
else if (string.IsNullOrEmpty(SearchSupv) == false)
{
employeeSuggestionsBindingSource.Filter = string.Format("[Supervisor] like '%{0 }%'", SearchSupv.Trim().Replace("'", "''"));
}
else if (string.IsNullOrEmpty(SearchAssigned) == false)
{
employeeSuggestionsBindingSource.Filter = string.Format("[Assigned To] like '%{0}%'", SearchAssigned.Trim().Replace("'", "''"));
}
else if (comboBoxCompleted.Text == "Incomplete")
{
employeeSuggestionsBindingSource.Filter = string.Format("[Completed]='False'");
}
else if (comboBoxCompleted.Text == "Completed")
{
employeeSuggestionsBindingSource.Filter = string.Format("[Completed]='True'");
}
必须有一种更简单的方法来过滤结果,我知道我可能以最坏的方式做到了......哈。
答案 0 :(得分:1)
如果我理解正确,您希望使用一个或多个谓词来构建过滤条件。您可以通过将多个条件与AND
组合在一起来实现此目的:
string filter = null;
if (StartDate < EndDate)
{
filter = CombineCriteria(
filter,
string.Format(
"[Suggestion Date] >= #{0:M/dd/yyyy}# AND " +
"[Suggestion Date] <= #{1:M/dd/yyyy}#",
StartDate,
EndDate));
}
if (string.IsNullOrEmpty(SearchEmp) == false)
{
filter = CombineCriteria(
filter,
string.Format(
"[Employee] LIKE '%{0}%'",
SearchEmp.Trim().Replace("'", "''")));
}
// ... more filter conditions ...
if (comboBoxCompleted.Text == "Incomplete")
filter = CombineCriteria(filter, "[Completed] = False");
else if (comboBoxCompleted.Text == "Completed")
filter = CombineCriteria(filter, "[Completed] = True");
employeeSuggestionsBindingSource.Filter = filter;
CombineCriteria()
如下:
private static string CombineCriteria(string oldCondition, string newCondition) {
if (string.IsNullOrEmpty(oldCondition))
return newCondition;
return "(" + oldCondition+ ") AND (" + newCondition + ")";
}