如何过滤DataGridView以仅保留给定的行集 [英] How to filter DataGridView to keep only a given set of rows

查看:45
本文介绍了如何过滤DataGridView以仅保留给定的行集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#中,我通过 DataSource 填充了 DataGridView .使用某些定制的过滤器,我可以确定行的子集(通过精确遍历行并检查列的条件),并且只需在DatGridView中保留/显示这些行.

In C# I have DataGridView populated via DataSource. With some custom made filter I determine a subset of rows (by looping through the rows and checking the conditions on columns, to be precise) and need to keep/show only these rows in the DatGridView.

我了解的一个选项是遍历网格并隐藏索引集之外的行.但是,这对于较大的行集来说非常缓慢.我的问题是:

One option I understand is to loop through the grid and hide the rows which are outside my index set. This, however, is painfully slow for larger set of rows. My question is:

给定一个绑定到数据源及其行的子集的datagridview,有没有一种有效的方法来仅将那些行保留在datagridview中?

given a datagridview which is bind to a datasource, and a subset of its rows, is there an efficient way to keep only those rows in datagridview?

推荐答案

速度慢可能仅来自GUI更新.您可能想要

Slow speed probably comes only from the GUI updates. You may want to

  • Suspend/ResumeLayout the DGV and/or
  • DoubleBuffer the DGV.

后者将加快包括滚动在内的所有显示操作.

The latter will speed up all display operations including scrolling.

  • 如果您想使用一个真正的过滤器,则需要一个额外的列来保存过滤器值和一个 BindingSource .

(如果您可以将逻辑放入过滤器中,则不需要多余的列.)

(You won't need the extra colum, if you can put your logic into the filter..)

假设 DataTable DT 作为您的 DataSource ,首先添加一个过滤器列:

Assuming a DataTable DT as your DataSource first add a filter column:

DT.Columns.Add("Filter", typeof(int));

接下来创建一个 BindingSource BS = new BindingSource();

现在将原始数据源绑定到该绑定源并将其用作新数据源:

Now bind the original datasource to the bindingsource and use it as the new datasource:

BS.DataSource = DT;
yourDGV.DataSource  = BS;

现在,您可以使用代码为过滤器列设置值,并最终设置或取消设置过滤器:

Now you can use your code to set a value for the filter column and finally set or unset the filter:

BS.Filter = "Filter = 23";  // use your indicator logic!
BS.Filter = "";              // unset filter

对于过滤器,您可以使用DataColumn.Expression属性

For the Filter you can use the DataColumn.Expression Property syntax.

  • 如果要查看过滤器列,还需要将其添加到DGV列中,并设置与数据源的连接.

示例:

yourDGV.Columns.Add("Filter", "filter");
yourDGV.Columns["Filter"].DataPropertyName = "Filter";

这篇关于如何过滤DataGridView以仅保留给定的行集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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