数据网格视图和空值上的多个筛选器
本文关键字:筛选 空值 数据网 网格 视图 数据 | 更新日期: 2023-09-27 18:30:57
所以我有一个包含许多列的数据网格视图,其中两列是"状态"和"分配给"。我有两个字段,用户应该能够根据他们键入的内容过滤所有行。我的代码如下所示:
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;
如果用户同时输入了状态和分配,则此方法非常有效,因为它将查找具有这两个筛选器的所有记录。但是,如果其中一个筛选器留空,例如状态 = "挂起"和分配 = ",它将按预期筛选记录,因此它将筛选状态为挂起和已分配为空的所有字段。问题是,如果用户将"已分配"留空,我希望它只是忽略过滤器中的此字段,而只是过滤所有"挂起"记录,而不考虑分配。
有什么想法吗?
编辑:我应该提到,为了简单起见,我在这里只包含两个过滤器。我的程序实际上有 6 个过滤器,因此过滤器字符串需要 6 个参数。
那么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 + "%'";
}
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 个参数,您可以添加更多参数,您需要做的就是"在 filt 变量中添加更多过滤器,然后再将其设置为 bs.filter"。希望你明白了。
尝试下面的代码
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;