0
votes

Hi I have a datagridview with multiselection set to true. How would I go about letting a user delete all BUT the selected rows in a datagridview?

I tried this, but it doesn't seem to work:

 For Each r As DataGridViewRow In DataGridView1.Rows
        If r.Selected = False Then
            DataGridView1.Rows.Remove(r)
        End If
    Next
3
i think you should use a loop like row(i).Selected = False then - ivan

3 Answers

0
votes

For Each loops use an Enumerator, and you're not supposed to change the data source for an enumerator while you're still looping through it.

There's likely a better way, but if all else fails you should be able to do this by adding references to each unselected row to a new list, and then looping through the list to remove them rows from the grid.

0
votes

Try this:

For Each r As DataGridViewRow In DataGridView1.Rows
            If r.Selected = False Then
                Dim row As String = r.ToString.Split("=")(1)(0)
                DataGridView1.Rows(row).Visible = False
            End If
        Next
0
votes

I suggest you to use LINQ here

  'This will selects all the selected rows in your Datagridview

  Dim sel_rows As List(Of DataGridViewRow) = (From row In DataGridView1.Rows.Cast(Of DataGridViewRow)() _
                                                  Where row.Selected = False).ToList()




 If MsgBox(String.Format("Do you want to delete {0} row(s)?", sel_rows.Count) _
              , MsgBoxStyle.Information + MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton3) = MsgBoxResult.Yes Then

     For Each row As DataGridViewRow In sel_rows
         If row.DataBoundItem IsNot Nothing Then
             DataGridView1.Rows.Remove(row)
         End If
     Next
 End If

Note : MsgBox() is optional !