简体   繁体   中英

Delete UNSELECTED rows in a datagridview

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

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.

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

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 !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM