Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing selected rows in dataGridView

I have a dataGridView that I populate with a list of files. I'd like to be able to remove some of those entries by selecting the entry (by clicking it) and then pressing the delete key. Here's the code I have so far:

private void DataGrid_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Delete)
    {
        foreach (DataGridViewRow r in DataGrid.SelectedRows)
        {
            if (!r.IsNewRow)
            {
                DataGrid.Rows.RemoveAt(r.Index);                        
            }
        }
    }
}

The problem is that it defines selected rows as all rows that were at one time clicked on. I would like to delete all highlighted rows. In other words, if a row is not highlighted it's not selected.

like image 495
Lukas Bystricky Avatar asked Sep 16 '25 04:09

Lukas Bystricky


1 Answers

This should work

private void DataGrid_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Delete)
    {
        Int32 selectedRowCount =  DataGrid.Rows.GetRowCount(DataGridViewElementStates.Selected);
        if (selectedRowCount > 0)
        {
            for (int i = 0; i < selectedRowCount; i++)
            {
                DataGrid.Rows.RemoveAt(DataGrid.SelectedRows[0].Index);
            }
        }
    }
}
like image 127
Benjamin Avatar answered Sep 18 '25 18:09

Benjamin