H H H H - 14 days ago 6
C# Question

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.

Answer

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);  
        }
     }
   }
}
Comments