Hayk
Hayk

Reputation: 687

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

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?

Upvotes: 0

Views: 577

Answers (2)

TaW
TaW

Reputation: 54453

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

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";

Upvotes: 1

Mr Mash
Mr Mash

Reputation: 1

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.

Upvotes: 0

Related Questions