How to filter DataGridView to keep only a given set of rows

只谈情不闲聊 提交于 2021-01-29 11:41:21

问题


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:

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?


回答1:


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.


  • If you'd rather go for a real filter you will need an extra column to hold the filter value and a BindingSource.

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

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

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

Next create a 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

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

  • If you want to see the filter column you need to add it to the DGV columns as well and set the connection to the datasource.

Example:

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



回答2:


How about you fill the Dgv from a code. Write a Select Statement to populate a DataTable then, proceed to setting the Datatable as DS for your datagridview then finally if you need to filter just call the querying method then it will call others aswell.



来源:https://stackoverflow.com/questions/56355044/how-to-filter-datagridview-to-keep-only-a-given-set-of-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!