Question DataGridView Deleting Selected rows...

tim8w

Active member
Joined
Oct 26, 2010
Messages
38
Programming Experience
5-10
This is such a basic question, I'm almost embarassed to ask it. How do I loop through seleted rows in a DataGridView and remove the rows?

I've tried this, but it doesn't work. After one row is removed, the index is all screwed up...

VB.NET:
            iIndex = dgvRecipe.Rows.GetNextRow(-1, DataGridViewElementStates.Selected)
            While iIndex <> -1
                dgvRecipe.Rows.RemoveAt(iIndex)
                iIndex = dgvRecipe.Rows.GetNextRow(iIndex, DataGridViewElementStates.Selected)
            End While
 
Last edited:
As jwavila reminded me on another forum...

VB.NET:
For iIndex = dgvRecipe.RowCount - 1 To 0 Step -1
    dgvRecipe.Rows.RemoveAt(iIndex)
Next iIndex
 
That would remove all rows wouldn't it? To remove just the selected rows you could do this:
VB.NET:
For Each row In myDataGridView.SelectedRows.Cast(Of DataGridViewRow)().ToArray()
    myDataGridView.Rows.Remove(row)
Next
 
Back
Top