Search code examples
c#winformsdatagridviewoledbrowfilter

Refreshing the RowFilter property on a DataView


Here is what I am trying to do. I have a form, with a 'filter' combobox and a DataGridView on it that displays the data from the database (I have assigned the data using the DataSet.Tables[0].DefaultView property. The combobox has a list of items, found in the database, plus a custom added one (named ). When the user selected one of the items, I the following code is run:

        int filterID = ( int )this.cbxFilter.SelectedValue;
        DataView view = this.dgvScenarios.DataSource as DataView;

        if ( filterID > 0 ) {
            view.RowFilter = string.Format( "Season = {0}", this.cbxFilter.SelectedValue );
        } else {
            view.RowFilter = string.Empty;
        }

Now, this works very well, as the <All> item is item 0. Now, I can change the 'filtering' property, Season, on the form. That has a similar combobox that has all of the same data in it as the 'filter' box, minus the <All> item. When the user changes this value, this is what is run:

        if ( this._loading ) {
            return;
        }

        ComboBox cbx = sender as ComboBox;
        int rows = this.UpdateDataFromControl( cbx.Tag, cbx.SelectedValue );

        if ( rows <= 0 ) {
            return;
        }

        this.UpdateDGVCell( cbx.Tag, cbx.SelectedValue, "ID" );
        this.UpdateDGVCell( cbx.Tag, cbx.Text, "Text" );

Now, I would think that the DataView would update the data grid, but it does nothing, and I can't figure out how to do this refresh without loading the data into the dataset again, which would be a hit to performance as I am accessing the database, again, and then filtering it out. Am I missing something that I haven't found on Google yet? Thanks for any help, and if anymore information is needed, please let me know!


Solution

  • Is there a reason you are using a DataView of the table, instead of using the table in a BindingSource? I have found the BindingSource easy to use.

    Somewhere in your code you probably have something like this:

    dataGridView.DataSource = yourDataSource;
    

    If you replace that with

    this.bindingSource = new BindingSource();
    this.bindingSource.DataSource = yourDataSource;
    dataGridView.DataSource = this.bindingSource;
    

    Then you can apply filtering (with the event automatically triggered to update the DataGridView display) as follows:

    this.bindingSource.Filter = "Season = 'x'"; //automatically updates the dataGridView
    

    To remove the filter, you can use

    this.bindingSource.RemoveFilter(); //automatically updates the dataGridView
    

    Does this address what you are trying to do?