DataGridView上的多个过滤器和空值

时间:2016-01-18 08:52:04

标签: c# datagridview

所以我有一个包含许多列的datagridview,其中两列是'Status'和'Allocated To'。我有两个字段,用户应该可以根据键入的内容过滤所有行。我的代码如下所示:

status = textBox1.Text;
allocated = textBox2.Text;

BindingSource bs = new BindingSource();
bs.DataSource = customerDataGridView.DataSource;

bs.Filter = "[Status] LIKE '%" + status + "%' AND [AssignedTo] LIKE '%" + allocated + "%'";
customerDataGridView.DataSource = bs;

如果用户同时输入了状态和分配,这很有效,因为它会找到包含这些过滤器的所有记录。但是,如果其中一个过滤器留空,那么说Status =“Pending”和Allocation =“”,它将按预期过滤记录,因此它将过滤Status为Pending且Allocated为空的所有字段。问题是,如果用户要将Allocated保留为空,我希望它只是忽略过滤器中的这个字段,只是过滤所有待处理记录而不管分配。

我是如何实现这一目标的?

编辑:我应该提一下,为简单起见,我在这里只包含了两个过滤器。我的程序实际上有6个过滤器,因此过滤字符串有6个参数。

3 个答案:

答案 0 :(得分:1)

那么if子句呢?

    string filterString = ""

    if(!string.IsNullOrEmpty(status)){
            filterString += "[Status] LIKE '%" + status + "%'";
    }
    if (!string.IsNullOrEmpty(allocated){
        if(!string.isNullOrEmpty(filterString) filterString += " AND ";
        filterString += "[AssignedTo] LIKE '%" + allocated + "%'";
    }

答案 1 :(得分:0)

尝试以下代码

status = textBox1.Text;
allocated = textBox2.Text;

BindingSource bs = new BindingSource();
bs.DataSource = customerDataGridView.DataSource;

if (!string.IsNullOrEmpty(status) && !string.IsNullOrEmpty(allocated))
    bs.Filter = "[Status] LIKE '%" + status + "%' AND [AssignedTo] LIKE '%" + allocated + "%'"; // both filter assign.
else if (string.IsNullOrEmpty(status))
    bs.Filter = "[AssignedTo] LIKE '%" + allocated + "%'"; // only allocated filter assign.
else //(string.IsNullOrEmpty(allocated))
    bs.Filter = "[Status] LIKE '%" + status + "%'"; // only status filter assign.

customerDataGridView.DataSource = bs;

答案 2 :(得分:0)

    status = textBox1.Text;
    allocated = textBox2.Text;

    BindingSource bs = new BindingSource();
    bs.DataSource = customerDataGridView.DataSource;

   var filt = "";


    if (!string.IsNullOrEmpty(status))
       {
         if(filt == "")
            filt  += "[Status] LIKE '%" + status + "%'";
         else
            filt += " And [Status] LIKE '%" + status + "%' ";
       }


      if (!string.IsNullOrEmpty(allocated))
           {
             if(filt == "")
                filt  += "[AssignedTo] LIKE '%" + allocated + "%'";
             else
                filt += " And [AssignedTo] LIKE '%" + allocated + "%' ";
           }

         if (!string.IsNullOrEmpty(param3))
          {
             if(filt == "")
                filt  += "[param3] LIKE '%" + param3+ "%'";
             else
                filt += " And [param3] LIKE '%" + param3+ "%' ";
          }

     bs.Filter = filt ;
    customerDataGridView.DataSource = bs;

依旧......

这个例子只有3个参数,你可以添加更多的参数,你需要做的只是“在设置为bs.filter之前在filt变量中添加更多过滤器”。 希望你能得到这个想法。