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.
When the Delete Button is clicked, the DataGridView CellContentClick event handler is executed. If the ColumnIndex is 3 i.e. the Delete Button is clicked, then a Confirmation MessageBox us show and if the User clicks Yes button the Row will be deleted (removed) from DataGridView and Database Table.
In this article, I will show you how to delete selected rows from a GridView in ASP.NET. We are using a checkbox inside a GridView and a button. The User selects the row from the checkbox that he want to delete and on a button click it is deleted from the GridView and from the database too.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With