How to delete selected rows from a DataGridView?
Solution 1
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.
Solution 2
if you are using a list of model, following code could help:
foreach (DataGridViewRow row in dataGridViewX.SelectedRows)
{
var val = (int)row.Cells[0].Value;
Products.Remove(Products.Find(d => d.ProductId == val));
}
dataGridViewX.DataSource = null;
dataGridViewX.DataSource = Products;
MKX2015
Updated on August 15, 2022Comments
-
MKX2015 almost 2 years
I have a
DataGridView
and aButton
. If rows are selected I want to delete them by clicking the button. I tried a couple of commands likeRemoveAt
,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.