使用数据表中的数据时如何过滤数据网格视图?VB.net

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41062859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 20:08:12  来源:igfitidea点击:

How to filter a datagridview when using data from datatable? VB.net

vb.netvb.net-2010

提问by Hywel

I have created a textbox and want it to search through a database of customers by name. Most of the questions are using an external dataset but this is just using a table created in the program using a csv file.

我创建了一个文本框,并希望它按名称搜索客户数据库。大多数问题都使用外部数据集,但这只是使用程序中使用 csv 文件创建的表。

回答by hypnos

You could take advantage from BindingSource, to be used as DataSource of your DataGridView. That way, acting on the BindingSource Filter property, you could set any type of filters, based on you columns name.

您可以利用BindingSource, 用作 DataGridView 的数据源。这样,根据 BindingSource 过滤器属性,您可以根据列名称设置任何类型的过滤器。

Please check the following snippet:

请检查以下代码段:

    Dim dt As New DataTable("Sample")
    dt.Columns.Add("Id")
    dt.Columns.Add("TimeStamp")

    For i As Int32 = 0 To 9999
        dt.Rows.Add(New Object() {i, DateTime.Now})
    Next

    Dim bs As New BindingSource
    bs.DataSource = dt

    bs.Filter = "Id > 10 AND Id < 20"

    DataGridView1.DataSource = bs

As you can see, i've defined a DataTable with two columns, namely "Id" and "TimeStamp". Then, with a simple loop i've populated my DataTable with some random records, for Id = 0 to Id = 9999.

如您所见,我定义了一个包含两列的 DataTable,即“Id”和“TimeStamp”。然后,通过一个简单的循环,我用一些随机记录填充了我的 DataTable,对于 Id = 0 到 Id = 9999。

After that, we declare a BindingSource, specifying its DataSource is our DataTable. On the Bindinf Source, we could set any filter, using the Filter property, the columns names, and the common logical operators.

之后,我们声明一个BindingSource,指定它的DataSource就是我们的DataTable。在 Bindinf Source 上,我们可以使用 Filter 属性、列名称和常用逻辑运算符来设置任何过滤器。

In my example, i've requested the filter to be on the only Id column, to visualize those record whose Id is between 11 and 19.

在我的示例中,我要求过滤器位于唯一的 Id 列上,以可视化那些 Id 介于 11 和 19 之间的记录。

Then, we could use the BindingSource as our DataGridView DataSource. And note that filters doesn't need to be apply before assigning the DataGridView DataSource: in fact, after the binding, each filter application will reflect immediately on the visualized rows.

然后,我们可以使用 BindingSource 作为我们的 DataGridView 数据源。并注意在分配 DataGridView 数据源之前不需要应用过滤器:实际上,在绑定之后,每个过滤器应用程序都会立即反映在可视化行上。

Hope this helps

希望这可以帮助