7

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

  • dg.CurrentCell - contains the previous clicked cell

  • dg.GetChildAt(...) - doesn't work because the cells are not listed as children of the DataGrid

5
  • Did you make a question and answer it right away, with an answer from msdn site, and dozen links on simple google search?
    – Claudius
    Apr 29, 2016 at 11:51
  • 1
    @Claudius did you notice that all the google results refer to DataGridView instead of DataGrid? If you add -datagridview to the search, every result is for WPF and so on...
    – Breeze
    Apr 29, 2016 at 11:56
  • But what is the difference if both grab same event Mouse.MouseDown?
    – Claudius
    Apr 29, 2016 at 12:03
  • well, what is the difference between a button and a datagridview? they both have the MouseDown-event... DataGridView is a lot more enhanced than DataGrid, maybe that's also why there isn't many help about DataGrid in forums or on SO
    – Breeze
    Apr 29, 2016 at 12:07
  • @Claudius I have to admit: when searching for the title and seeing that DataGridView.HitTest exists it could come to your mind that DataGrid.HitTest is worth looking up, but for anybody searching for the title plus -datagridview -wpf (to get results for DataGrid) the question might be helpful
    – Breeze
    Apr 29, 2016 at 12:14

2 Answers 2

7

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
3
  • Shouldn't clickedCell be of type DataGridViewCell? Apr 24, 2018 at 22:14
  • @CrazyIvan1974 I was unfortunately bound to the ancient DataGrid WinForms control. I'm joyful if it also works for DataGridView
    – Breeze
    Apr 25, 2018 at 5:58
  • Yeah, wow, my mistake. I see NOW that this topic is not about the DataGridView. Blew right past the main topic. This DOES work with DataGridView. Apr 30, 2018 at 15:08
1
   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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.