Search code examples
c#datagridviewinvisibledatagridviewrow

Faster Method to Making DataGridViewRow's non-Visible


I'm using the following code to set a bunch of DataGridViewRow elements to be invisible. The rule I am using is to check the associated datasource for a boolean flag. If the flag is true, the row will be displayed. If not, it will be invisible.

The following code works; however, it does so by consuming quite a bit of time:

CurrencyManager currencyManager = (CurrencyManager)BindingContext[dataGridView.DataSource];

currencyManager.SuspendBinding();

foreach (DataGridViewRow row in dataGridView.Rows)
{
    if (!objectList.list[row.Index].Selected)
    {
        row.Visible = false;
    }
}
currencyManager.ResumeBinding();

Does anyone have a better solution? The longer the list of objects I have to go through, the longer this process takes, naturally. I cannot set a range of cells because the boolean values may not be contiguous.


Solution

  • As PraVn had said, you could simply filter prior to using the datagridview. If you are using a DataSet, DataTable, or DataView just do the this:

    DataSet ds = new DataSet();
    ds.Tables[0].DefaultView.RowFilter = "YourBooleanColumn = 1";
    
    DataView dv = new DataView();
    dv.RowFilter = "YourBooleanColumn = 1";
    
    DataTable dt = new DataTable();
    dt.RowFilter.DefaultView.RowFilter = "YourBooleanColumn = 1";
    

    Alternatively, you can could filter at the database end (if there is one?). Let us know what your data source is and I'll update as appropriate. This is the best I can do!