删除datagridview中的UNSELECTED行

时间:2015-11-18 22:31:01

标签: vb.net linq datagridview

您好我有一个datagridview,其multiselection设置为true。 我如何让用户删除所有但是在datagridview中删除所选行?

我尝试了这个,但它似乎不起作用:

 For Each r As DataGridViewRow In DataGridView1.Rows
        If r.Selected = False Then
            DataGridView1.Rows.Remove(r)
        End If
    Next

3 个答案:

答案 0 :(得分:0)

For Each循环使用枚举器,并且您不应该更改枚举器的数据源,而您仍在循环播放它。

可能有更好的方法,但是如果所有其他方法都失败了,你应该能够通过将每个未选择的行的引用添加到新列表,然后循环遍历列表以从网格中删除它们来实现此目的

答案 1 :(得分:0)

试试这个:

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

答案 2 :(得分:0)

我建议你在这里使用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()是可选的!

相关问题