编辑和过滤数据网格视图所需的设计建议 [英] Design advise needed on editing and filtering a datagridview

查看:21
本文介绍了编辑和过滤数据网格视图所需的设计建议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个涉及 DataGridView 和 DataTable 的设计问题,它们由 WinForms 应用程序中的 BindingSource 绑定.DataTable 由 sql server 表填充.

I have a design question that involves DataGridView and DataTable, bound by a BindingSource in a WinForms application. The DataTable is populated by a sql server table.

用户可以在 DataGrid 中添加新行、删除行和编辑行.
完成后,他单击一个按钮,该按钮将开始循环遍历 DataTable,这将根据他在 DataGridView 中所做的操作来编辑一些表、插入到一些表中并从一些表中删除.

The user can add new rows in the DataGrid, delete rows and edit rows.
When he is done he clicks on a button which will start a loop through the DataTable which will edit some tables, insert into some table and delete from some tables depending on what he did in the DataGridView.

这一切都没有问题,而且工作正常.但是现在我必须让用户也过滤数据,所以 DataGridView 会显示更多或更少的记录.

This is all no problem and it works fine. But now I have to let the user also filter the data, so the DataGridView will show more or less records.

这里的问题是,当用户添加新行、删除几行、更改几行,然后应用可以过滤掉一个或多个这些记录的过滤器时,按钮中的循环仍然应该看到处理这些记录.

The problem here is that when the user adds a new row, deletes a few rows, changes a few rows, and than applies a filter that could filter out one or more of these records, the loop in the button should still see these records to process them.

处理这个问题的最佳设计是什么?

What is the best design for handling this ?

推荐答案

过滤器不应影响循环.例如,在下面的代码中,我从具有应用过滤器的 DataTable 设置了 DataGridView.DataSource 并循环遍历表,打印值:

The filter shouldn't affect the loop. For example, in the following code I set the DataGridView.DataSource from a DataTable that has an applied filter and loop through the table, printing values:

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 行仍然会打印每个条目.

With the filter, the DataGridView displays only select entries. But looping through the DataTable rows still prints every entry.

因此,在处理诸如 BindingSource 之类的绑定时,在 DataGridView 已经获得源之后,您可能会像这样更改过滤器以获得动态搜索选项:

Therefore, when handling binding such as a BindingSource, after the DataGridView is already sourced, you might change your filter like so to have a dynamic searching option:

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);
}

这篇关于编辑和过滤数据网格视图所需的设计建议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆