Breeze
Breeze

Reputation: 2058

Get DataGrid cell from mouse position

I want to get the clicked cell of a DataGrid at the MouseDown event. So far I haven't been successful.
I tried

Upvotes: 7

Views: 7460

Answers (2)

Ahmet OYMACI
Ahmet OYMACI

Reputation: 11

   Private Sub DataGridView1_MouseDown(sender As Object, e As MouseEventArgs) Handles DataGridView1.MouseDown
    Try
        With DataGridView1
            .Rows(.HitTest(e.X, e.Y).RowIndex).Selected = True
        End With
    Catch
    End Try
End Sub

Upvotes: 1

Breeze
Breeze

Reputation: 2058

You can use HitTest to get the cell that the mouse is over. (It is not dependant on the MouseDown-Event, you just need the mouse position relative to the DataGrid)

example:

Private Sub dg_MouseDown(sender As Object, e As MouseEventArgs) Handles dg.MouseDown
    Dim htinfo As HitTestInfo = dg.HitTest(new Point(e.X, e.Y))

    If htinfo.Type = HitTestType.Cell Then
        Dim clickedCell As DataGridCell = dg.Item(htinfo.Row, htinfo.Column)
    End If
End Sub

Upvotes: 7

Related Questions