您好,我有一个多选设置为true的datagridview。我该如何让用户删除datagridview中除选定行之外的所有行?
我试过了,但似乎不起作用:
 For Each r As DataGridViewRow In DataGridView1.Rows
        If r.Selected = False Then
            DataGridView1.Rows.Remove(r)
        End If
    Next发布于 2015-11-19 06:33:38
For Each循环使用枚举器,当您仍在遍历枚举器时,不应该更改该枚举器的数据源。
可能有一种更好的方法,但如果所有其他方法都失败了,您应该能够通过将对每个未选中行的引用添加到新列表中,然后循环遍历列表以从网格中删除它们。
发布于 2015-11-19 07:03:31
试试这个:
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发布于 2015-11-19 12:51:49
我建议你在这里使用LINQ
  '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注意:MsgBox()是可选的!
https://stackoverflow.com/questions/33791712
复制相似问题