我如何通过检查checklistbox中的多个项目来过滤dataGridView
本文关键字:项目 过滤 dataGridView 何通过 检查 checklistbox | 更新日期: 2023-09-27 18:11:37
我有这个代码过滤我的dataGridView使用checkedListBox。每次用户选中checkedListBox中的一个框时,dataGridView自动更新,只显示与选中的名称相关的数据(例如,通过checked name = "John"过滤),它工作得很好。
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
DataTableCollection tables = myDatabaseDataSet.Tables;
DataView view = new DataView(tables[0]);
BindingSource source = new BindingSource();
source.DataSource = view;
dataGridView1.DataSource = source;
source.Filter = "myColumnName ='" + checkedListBox1.Text.Replace("'", "''") + "'";
}
现在的问题是,我怎么能使它在checkedListBox中的多个项目被选中,而反过来dataGridView更新只显示被选中的名字(例如checkkedlistbox中的被选中的名字是"约翰"answers"简")?
上面的代码给出了以下结果:
上面代码我想达到的是这个(模拟图片):
期望结果因此,您将拥有一个数据库,它将导致某种形式的"从数据库中选择不同的名称"来填充checkedListBox。所以现在你需要添加如下内容:
List<string> names = new List<string>();
for (int i = 0; i < checkedListBox.Items.Count; i++)
{
CheckState st = checkedListBox.GetItemCheckState(checkedListBox.Items.IndexOf(i));
if(st == CheckState.Checked)
{
int selected = checkedListBox.SelectedIndex;
if (selected != -1)
{
names.Add(checkedListBox.Items[selected].ToString());
}
}
}
结果将是checkedListBox中被选中的项的列表。然后,您可以将它与我之前给出的代码一起用于过滤。只需将硬编码的名称替换为检查列表字符串。
string filterString = "";
int count = 0;
foreach (name in names)
{
if (count != 0)
{
filterString += " OR Responsible = '" + name + "'";
}
else
{
filterString += "Responsible = '" + name + "'";
}
count += 1;
}
现在您有了一个字符串,可以用作创建DataView的过滤器:
DataView view = new DataView(tables[0], filterString, "Responsible Desc", DataViewRowState.CurrentRows);
这应该在表变成DataView时过滤它,而不是之后,根据checkBox状态。
最后的事件:
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
DataTableCollection tables = myDatabaseDataSet.Tables;
//
// Place all my code here
//
BindingSource source = new BindingSource();
source.DataSource = view;
dataGridView1.DataSource = source;
}