Click here to Skip to main content
15,916,462 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi, Iam using VS2010. C#. Windows Forms Applications..
When I wish to delete multiple rows, Iam using the below codes, but It's
deleting a single first selected row only and not all selected multiple rows..

Does anybody can help me?

C#
for each (DataGridViewRow^ Tw in myDataGrid1->Rows){
    if(Tw->Selected==true){
        //DJDtb->Rows[myDataGrid1->CurrentRow->Index]->Delete();
        myDataGrid1->Rows->Remove(Tw);
    }
}


Thanks
Posted
Updated 25-Apr-15 2:34am
v2

Hi If you are looking a way in C# the below solution is too much easy solution:

C#
private void buttonRemove_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
        {
            if (oneCell.Selected)
                dataGridView1.Rows.RemoveAt(oneCell.RowIndex);
        }
    }


But in C++ it is like this, however in C# version you can use also .SelectedRows too:

C++
foreach (DataGridViewRow row in DataGridView1.SelectedRows) 
{
    DataGridView1.Rows.Remove(row);
}


Also you can follow the below useful links:
https://www.youtube.com/watch?v=ElCHMYjRFO0[^]
http://stackoverflow.com/questions/2084346/how-to-delete-a-selected-datagridviewrow-and-update-a-connected-database-table[^]
https://social.msdn.microsoft.com/forums/windows/en-us/3493f264-58d4-45c4-a1a8-575a09a9b9cd/deleting-a-selected-row-in-datagrid-view[^]
 
Share this answer
 
v2
Comments
Retentive Emmanuel 24-Mar-16 9:28am    
please I want this in VB

private void buttonRemove_Click
( object sender, EventArgs e)
{
foreach (DataGridViewCell
oneCell in
dataGridView1.SelectedCells)
{
if (oneCell.Selected)
dataGridView1.Rows.RemoveAt
(oneCell.RowIndex);
}
}
That's not C# - it's C++.

The two are not interchangeable.

In C#, that operation is forbidden: you cannot alter the list that a foreach loop is iterating through, and I would assume that your code is throwing an exception when you try.
 
Share this answer
 
Comments
Paramu1973 25-Apr-15 8:50am    
No any exceptions...In DataGridView First Selected One Row only disappearing...Not All Selected rows.. Thanks

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