Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I have a datagridview and i put may array like this

BindingList<person> p1;
private void loadgrid()
        {
            p1 = new BindingList<person>();
            p1.Add(new person() { PersonId = 1, Person_Name = "reden" });
            p1.Add(new person() { PersonId = 2, Person_Name = "anne" });
            dataGridView1.DataSource = p1;
        }

and i will call this method to view the data that i put

and to delete each of an array i do this

private void button1_Click(object sender, EventArgs e)
        {

            p1.RemoveAt(dataGridView1.SelectedRows[0].Index);
        }

my question is how can i do a multiple delete using this?

What I have tried:

i tried this one but did not work
foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
                {
                    p1.RemoveAt(dataGridView1.SelectedRows[0].Index);
                }   
Posted
Updated 17-Sep-18 23:40pm

1 solution

I think your code should be like this:
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
    if (!row.IsNewRow)
    {
        dataGridView1.Rows.Remove(row);
    }
}
 
Share this answer
 
v3
Comments
Richard Deeming 18-Sep-18 13:00pm    
Depending on how it's implemented, that might produce a "collection has been modified" exception, since the SelectedRows is based on the Rows, and you're modifying that collection within the loop.

I'd be inclined to bung a .ToList() in there to avoid the problem:
foreach (DataGridViewRow row in dataGridView1.SelectedRows.ToList())
RickZeeland 18-Sep-18 15:15pm    
Well I did a quick test, using an XML datasource and that worked.
But a better approach would be to delete the items in the Bindinglist I think ...
Richard Deeming 18-Sep-18 15:19pm    
That's interesting. Does the row you've just removed disappear from the SelectedRows collection? And if you've got more than one selected row, does the SelectedRows collection still iterate over them all?
RickZeeland 18-Sep-18 15:26pm    
I don't have my test code available at the moment, but I will test it tomorrow, promise :)
RickZeeland 19-Sep-18 2:10am    
I can confirm the removed row disappears from the SelectedRows collection.
The only problem I found was with the bottom new row selected, so I updated the solution to fix that.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900