我改编了这个问题的代码 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
答案 0 :(得分:1)
我认为你不能同时使用全列和全行选择,在运行一些测试之后,似乎更改datagridview的selectionmode是在设置时清除选择...所以除非你要创建一个继承自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