我正在处理一个新项目,该项目需要用户在数据网格视图中进行多行选择/取消选择,只需轻触触摸屏即可。
表单应如下所示:
例如,如果用户想删除第2行和第5行,则只需在每行上点击一次即可选择/取消选择它们。选择完成后,他点击"删除行"按钮。
我已经尝试过使用CellClick事件但没有成功!!
有人能够知道我该如何处理这个问题?
答案 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