datagridview中的多个选择

时间:2017-01-18 20:45:54

标签: vb.net winforms datagridview

我正在处理一个新项目,该项目需要用户在数据网格视图中进行多行选择/取消选择,只需轻触触摸屏即可。

表单应如下所示:

Form Screenshot http://117.imagebam.com/download/PBhJJNednkL1q0JzMF8j_g/52716/527152884/test%20lecture%20scanner.PNG

例如,如果用户想删除第2行和第5行,则只需在每行上点击一次即可选择/取消选择它们。选择完成后,他点击"删除行"按钮。

我已经尝试过使用CellClick事件但没有成功!!

有人能够知道我该如何处理这个问题?

1 个答案:

答案 0 :(得分:1)

MultiSelect属性设置为True并将SelectionMode设置为FullRowSelect后,您可以使用List存储DataGridView的哪一行地选择。

CellClick上,您可以在List上添加/删除行,RowPostPaint如果List中包含该行,则可以选择一行RowsRemoved您需要清除List

Private intSelectedRows As New List(Of Integer)

Private Sub DataGridView1_CellClick(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick

    With CType(sender, DataGridView)

        Dim intRow As Integer = .CurrentRow.Index

        If Not Me.intSelectedRows.Contains(intRow) Then
            Me.intSelectedRows.Add(intRow)
        Else
            .CurrentRow.Selected = False
            Me.intSelectedRows.Remove(intRow)
        End If

    End With

End Sub

Private Sub DataGridView1_RowPostPaint(sender As Object, e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles DataGridView1.RowPostPaint

    If Me.intSelectedRows.Contains(e.RowIndex) Then
        CType(sender, DataGridView).Rows(e.RowIndex).Selected = True
    End If

End Sub

Private Sub DataGridView1_RowsRemoved(sender As Object, e As System.Windows.Forms.DataGridViewRowsRemovedEventArgs) Handles DataGridView1.RowsRemoved

    Me.intSelectedRows.Clear()

End Sub

如果您想清除选择,可以使用以下代码:

Private Sub btnClearSelectedRows_Click(sender As System.Object, e As System.EventArgs) Handles btnClearSelectedRows.Click

    For Each intSelectedRow As Integer In Me.intSelectedRows
        Me.DataGridView1.Rows(intSelectedRow).Selected = False
    Next intSelectedRow

    Me.intSelectedRows.Clear()

End Sub