多个绑定源过滤器

时间:2013-11-20 14:11:22

标签: c#

我有一个简单的数据库,我试图让它可以用多个标准进行搜索。我不知道的是如何让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'");
}    

必须有一种更简单的方法来过滤结果,我知道我可能以最坏的方式做到了......哈。

1 个答案:

答案 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 + ")";
}