我正在尝试制作一个包含多个Comboboxes
的搜索过滤器,
代码工作,但只是在第一次测试中,问题是当我想在datagirdview
上显示任何内容后进行另一次搜索时。
这是代码,我不知道这个问题是什么?
string aFilter = string.Empty;
string bFilter = string.Empty;
string cFilter = string.Empty;
private void applyFilter()
{
generateFilter(bFilter);
generateFilter(cFilter);
}
private void generateFilter(string filter)
{
if (!string.IsNullOrEmpty(filter))
{
if (string.IsNullOrEmpty(aFilter))
{
aFilter = filter;
}
else
{
aFilter += " AND " + filter;
}
}
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
DataView dv = new DataView(table);
bFilter = string.Format("[Nom complet] LIKE '%{0}%'", comboBox2.SelectedItem.ToString());
applyFilter();
dv.RowFilter = aFilter;
dataGridView1.DataSource = dv;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataView dv1 = new DataView(table);
cFilter = string.Format("[Type programme] LIKE '%{0}%'", comboBox1.SelectedItem.ToString());
applyFilter();
dv1.RowFilter = aFilter;
dataGridView1.DataSource = dv1;
}
答案 0 :(得分:0)
问题是aFilter
。每个过滤器一次又一次地添加到它。
尝试:
string bFilter = "";
string cFilter = "";
private string CombinFilters()
{
var a = new[] { bFilter, cFilter }; //all filters to combin
var notNull = a.Where(x => !string.IsNullOrWhiteSpace(x));
if (notNull.Any())
return string.Join(" AND ", notNull);
else
return null;
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
DataView dv = new DataView(table);
bFilter = string.Format("[Nom complet] LIKE '%{0}%'", "123");
dv.RowFilter = CombinFilters();
dataGridView1.DataSource = dv;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataView dv = new DataView(table);
cFilter = string.Format("[Type programme] LIKE '%{0}%'", "345");
dv.RowFilter = CombinFilters();
dataGridView1.DataSource = dv;
}