Search code examples
c#winformsdatagridviewdatagridviewcolumn

How to hide a row of a DataGridView when clicking on a DataGridViewColumnButton?


I have added a DataTable to the DataGridView in WinForms SystemTray App. I have two buttons in each row, like "public" and "Ignore". When I click any of the two buttons the particular row which the buttons have the same index must be hidden.


Solution

  • If you want to hide the DataGridViewRow in which a user clicked a button use the DataGridView's CellClick event, like this:

    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) {
        // After you've verified that the column clicked contains the button you want to use to hide rows...
    
        CurrencyManager currencyManager1 = (CurrencyManager)BindingContext[dataGridView1.DataSource];
        currencyManager1.SuspendBinding();
    
        dataGridView1.Rows[e.RowIndex].Visible = false;
    
        currencyManager1.ResumeBinding();
    }
    

    Notice that you need to suspend data binding to set the row's Visible property to false.

    To display all the rows you've hidden rebind your DataGridView:

    dataGridView1.DataSource = null;         
    dataGridView1.DataSource = yourDataTable;