我有一个涉及DataGridView和DataTable的设计问题,它由WinForms应用程序中的BindingSource绑定。 DataTable由sql server表填充。
用户可以在DataGrid中添加新行,删除行和编辑行 当他完成后,他点击一个按钮,它将通过DataTable开始一个循环,它将编辑一些表,插入到某些表中,并根据他在DataGridView中的操作从一些表中删除。
这都没问题,而且运行正常。 但是现在我必须让用户也过滤数据,因此DataGridView将显示更多或更少的记录。
这里的问题是当用户添加新行时,删除几行,更改几行,然后应用可以过滤掉一个或多个这些记录的过滤器,按钮中的循环仍然应该看到这些记录来处理它们。
处理此问题的最佳设计是什么?
答案 0 :(得分:2)
过滤器不应影响循环。例如,在以下代码中,我从DataGridView.DataSource
设置了DataTable
,该DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Quantity", typeof(int));
dt.Rows.Add("Foo", 1);
dt.Rows.Add("Bar", 2);
dt.Rows.Add("Baz", 3);
string filterField = "Name";
string filterText = "B";
dt.DefaultView.RowFilter = string.Format("[{0}] LIKE '%{1}%'", filterField, filterText);
this.dataGridView1.DataSource = dt;
foreach (DataRow row in dt.Rows)
{
Console.WriteLine("{0}", row.ItemArray[0]);
}
具有应用过滤器并循环遍历表格,打印值:
DataGridView
使用过滤器,DataTable
仅显示选择条目。但循环遍历BindingSource
行仍会打印每个条目。
因此,处理DataGridView
之类的绑定时,在private void textBox1_TextChanged(object sender, EventArgs e)
{
BindingSource bs = this.dataGridView1.DataSource as BindingSource;
DataTable dt = bs.DataSource as DataTable;
dt.DefaultView.RowFilter = string.Format("[{0}] LIKE '{1}%'", "Name", this.textBox1.Text);
}
已经来源之后,您可能会更改过滤器,以便拥有动态搜索选项:
include
答案 1 :(得分:1)
我刚刚发现了一种更好的方法来过滤mj82发布的DataGridView
问题(是的,这是一个问题):
Filtering DataGridView without changing datasource
这是问题中最有用的部分。
DataTable dt = new DataTable();
BindingSource bs = new BindingSource();
private void Form1_Load(object sender, EventArgs e)
{
dt.Columns.Add("id", typeof(int));
dt.Columns.Add("country", typeof(string));
dt.Rows.Add(new object[] { 1, "Belgium" });
dt.Rows.Add(new object[] { 2, "France" });
dt.Rows.Add(new object[] { 3, "Germany" });
dt.Rows.Add(new object[] { 4, "Spain" });
dt.Rows.Add(new object[] { 5, "Swiss" });
dt.Rows.Add(new object[] { 6, "United Kingdom" });
bs.DataSource = dt;
dataGridView1.DataSource = bs;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
MessageBox.Show("DataSource type BEFORE = " + dataGridView1.DataSource.GetType().ToString());
bs.Filter = string.Format("country LIKE '%{0}%'", textBox1.Text);
MessageBox.Show("DataSource type AFTER = " + dataGridView1.DataSource.GetType().ToString());
}