I have a DataGridView
and a Button
. If rows are selected I want to delete them by clicking the button. I tried a couple of commands like RemoveAt
, SelectedRows
etc., but nothing did work. How can I solve that?
I tried something like:
if (dataGridView2.SelectedRows.Count > 0)
{
DataGridViewSelectedRowCollection rows = dataGridView2.SelectedRows;
dataGridView2.Rows.RemoveAt(rows);
}
but the RemoveAt method does only accept integers. Before I tried it with Selected Cells but then he delets all rows because there is always a cell selected.
If you just want to remove the selected rows from the DataGridView
this should do it:
foreach (DataGridViewRow row in yourDataGridView.SelectedRows)
{
yourDataGridView.Rows.RemoveAt(row.Index);
}
Your code didn't work because you've used RemoveAt(rows)
but RemoveAt
accepts only the index of the row which you want to remove. You are passing a DataGridViewSelectedRowCollection
to it. You can get the index of a row via DataGridViewRow.Index
as shown above.