Reputation: 51
I adapted code from this question how to select rows on cellclick, and also columns on column header click? into a single DataGridView1_MouseDown event, because it wasn't allowing me to select multiple rows/columns using the "Ctrl" key.
What I'd like, is to be able to select multiple rows (clicking on the row indices) OR multiple columns (clicking on the column headers) by selecting one after another keeping "Ctrl" pressed. I can easily get one OR the other (setting DataGridViewSelectionMode to either FullRowSelect or ColumnHeaderSelect) and then Ctrl works, but I'd like to have both functionality on the same DataGridView.
I feel like I'm so close. Thanks for any tips!
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
Upvotes: 3
Views: 1383
Reputation: 2360
I don't think you will be able to use both full column and full row select at the same time, after running some tests, it seems that changing the datagridview's selectionmode is what's clearing selections when it is set...so unless you were to create a custom control that inherits from datagridview and overrides some of its internals, you may be stuck. Without doing that, the only way I was able to achieve the behavior you're trying to get was to leave the datagridview cellselection mode set to cellselect, and do the row/column selections manually:
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
Upvotes: 1