Boushard
Boushard

Reputation: 57

Multiple selection in datagridview

I work on a new project that need a multiple row selection/deselection by the user in a datagridview with only a tap on a touch screen.

The form should look like this:

Form Screenshot

For exemple, if the user want to delete row 2 and 5, he only need to tap once on each line to select/deselect them. After the selection is done, he tap on "Delete Row" button.

I've already try to play with the CellClick event without success!!

Can someone have a clue how can I handle this problem?

Upvotes: 2

Views: 4466

Answers (1)

tezzo
tezzo

Reputation: 11105

After setting MultiSelect property to True and SelectionMode to FullRowSelect you can use a List to store which row of your DataGridView is selected.

On CellClick you can add/remove rows from your List, on RowPostPaint you can select a row if it's included in the List and on RowsRemoved you have to clear the 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

If you want to clear selection you can use this code:

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

Upvotes: 4

Related Questions