3
votes

I have a DataGridView control on a form (Form1.vb) and need to allow a user to multiselect rows without using the CTRL key (no keyboard is available - they are using a touch screen). I have enabled the mutliselect property and have the following code in my Form class.

My DataGridView is called dgvOEE and I've created a List of selected rows which I add to and remove rows as they are clicked via the "CellClick" event. I then select the row via the PerformSelection routine.

Private selectedRows As New List(Of DataGridViewRow)

 Private Sub dgvOEE_CellClick(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvOEE.CellClick
    If (selectedRows.Contains(dgvOEE.Rows(e.RowIndex))) Then
        selectedRows.Remove(dgvOEE.CurrentRow)
    Else
        selectedRows.Add(dgvOEE.CurrentRow)
    End If
    PerformSelection()
End Sub

Private Sub PerformSelection()
    For Each dgvRow As DataGridViewRow In dgvOEE.Rows
        If (selectedRows.Contains(dgvRow)) Then
            dgvRow.Selected = True
        Else
            dgvRow.Selected = False
        End If
    Next
End Sub

The issue with this method is that each time a user clicks down on any cell it unhighlights/unselects anything already selected and then runs my code. It causes "flicker". I believe I need to capture/override the DataGridView mousedown. The examples I've seen are something like this (which I can put into my current form class, but how do I implement something like this to capture the event of the DataGridView on my form?? This example creates a class called MyDataGrid which inherits DataGridView and is supposed to capture the OnCellMouseDown, but not sure how this class within my form class works (how to implement?)

Public Class MyDataGrid
    Inherits DataGridView

    Protected Overrides Sub OnCellMouseDown(ByVal e As System.Windows.Forms.MouseEventArgs)
        MyBase.OnCellMouseDown(e)
    End Sub
End Class 

Maybe an EventHandler somehow? Any help and code examples would be appreciated.

Kindest Regards

1
Sorry, I've retracted my answer as it was a load of BS. I've had a look at overriding the OnCellMouseDown event, but I can't see an obvious way to do the selection without the control key... If you find the solution to this please post back.yu_ominae
Can you track two clicks and for while a range of cells?ZL1Corvette

1 Answers

1
votes

Creating a sub class of the DataGridView will work if you override the OnMouseDown and OnMouseUp methods like so:

Public Class SimpleMultiselectDataGridView
    Inherits DataGridView

    Protected Overrides Sub OnCellMouseDown(e As DataGridViewCellMouseEventArgs)
        Me.Rows(e.RowIndex).Selected = Not Me.Rows(e.RowIndex).Selected
    End Sub

    Protected Overrides Sub OnCellMouseUp(e As DataGridViewCellMouseEventArgs)
    End Sub
End Class

Then you can simply change the type of your DataGridView to SimpleMultiselectDataGridView.