Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete selected rows from a DataGridView?

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.

like image 465
MKX2015 Avatar asked Feb 19 '15 09:02

MKX2015


People also ask

How do I delete a row from GridView in Windows app?

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.

How can we delete selected row from GridView and database in asp net?

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.


2 Answers

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.

like image 163
Tim Schmelter Avatar answered Oct 25 '22 16:10

Tim Schmelter


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;
like image 44
Ravi Anand Avatar answered Oct 25 '22 18:10

Ravi Anand