我改编了这个问题的代码 how to select rows on cellclick, and also columns on column header click? 到单个 DataGridView1_MouseDown 事件中,因为它不允许我使用“Ctrl”键选择多行/多列。
我想要的是能够通过按住“Ctrl”键一个接一个地选择多行(单击行索引)或多列(单击列标题)。我可以很容易地获得一个或另一个(将 DataGridViewSelectionMode 设置为 FullRowSelect 或 ColumnHeaderSelect)然后 Ctrl 工作,但我想在同一个 DataGridView 上同时拥有这两种功能。
我觉得我很亲近。感谢您提供任何提示!
Private Sub DataGridView1_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseDown
Dim ht As DataGridView.HitTestInfo
ht = Me.DataGridView1.HitTest(e.X, e.Y)
If e.Button = Windows.Forms.MouseButtons.Left Then
If ht.Type = DataGridViewHitTestType.Cell Then
DataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect
DataGridView1.CurrentCell.Selected = True
ElseIf ht.Type = DataGridViewHitTestType.RowHeader Then
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
DataGridView1.Rows(ht.RowIndex).Selected = True
ElseIf ht.Type = DataGridViewHitTestType.ColumnHeader Then
DataGridView1.SelectionMode = DataGridViewSelectionMode.ColumnHeaderSelect
DataGridView1.Columns(ht.ColumnIndex).Selected = True
End If
End If
End Sub
最佳答案
我认为您不能同时使用整列和整行选择,在运行一些测试后,似乎更改 datagridview 的选择模式就是在设置时清除选择...所以除非您要创建一个继承自 datagridview 并覆盖其某些内部结构的自定义控件,否则您可能会被卡住。如果不这样做,我能够实现您想要获得的行为的唯一方法是将 datagridview cellselection 模式设置为 cellselect,并手动进行行/列选择:
Private Sub DataGridView1_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) _
Handles DataGridView1.MouseDown
If e.Button = Windows.Forms.MouseButtons.Left Then
Dim ht As DataGridView.HitTestInfo = Me.DataGridView1.HitTest(e.X, e.Y)
If Not My.Computer.Keyboard.CtrlKeyDown Then DataGridView1.ClearSelection()
If ht.Type = DataGridViewHitTestType.Cell Then
DataGridView1.CurrentCell.Selected = True
ElseIf ht.Type = DataGridViewHitTestType.RowHeader Then
For i As Integer = 0 To DataGridView1.Columns.Count - 1
DataGridView1.Rows(ht.RowIndex).Cells(i).Selected = True
Next
ElseIf ht.Type = DataGridViewHitTestType.ColumnHeader Then
For i As Integer = 0 To DataGridView1.Rows.Count - 1
DataGridView1.Rows(i).Cells(ht.ColumnIndex).Selected = True
Next
End If
End If
End Sub
关于vb.net - 如何选择多行或列保持 "Ctrl"在 DataGridView 对象中按下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41278105/