Is there a datagrid mouse down hit test to get the row and column index of the click?

4.1k views Asked by At

With Winforms' DataGridView, one could use HitTest to determine the column and row index of the mouse down (and other events).

Dim hti As DataGridView.HitTestInfo = sender.HitTest(e.X, e.Y)

Is there something similar with WPF's DataGrid? I need to get the row and column indexes for the MouseLeftButtonDown event.

2

There are 2 answers

1
mm8 On BEST ANSWER

It's a bit more complicated than this but the following links should be helpful in getting the index of the row and column.

WPF DataGrid - detecting the column, cell and row that has been clicked: http://blog.scottlogic.com/2008/12/02/wpf-datagrid-detecting-clicked-cell-and-row.html

WPF DataGrid - get row number which mouse cursor is on

You will have to use the VisualTreeHelper class to traverse the Visual elements that make up the DataGrid as explained above.

0
user1500403 On

For those that may wish to avoid my search here is the total code I ended up puzzling together that is able to deliver:

  1. Current row index

  2. Current Column index

  3. Current Column header And

  4. is able to expose the value/s of columns on the row.

    The code goes into MouseLeftButtonup event and DGrid1 is the name of the grid

    Dim currentRowIndex As Integer = -1
    Dim CurrentColumnIndex As Integer = -1
    Dim CurrentColumnHeader As String = ""
    Dim Myrow As DataRowView = Nothing
    Dim dep As DependencyObject = DirectCast(e.OriginalSource, DependencyObject)
    While dep IsNot Nothing And Not TypeOf dep Is DataGridCell And Not TypeOf dep Is Primitives.DataGridColumnHeader
        dep = VisualTreeHelper.GetParent(dep)
        If dep IsNot Nothing Then
            If TypeOf dep Is DataGridCell Then
                Dim cell As DataGridCell = DirectCast(dep, DataGridCell)
                Dim col As DataGridBoundColumn = DirectCast(cell.Column, DataGridBoundColumn)
                Myrow = DGrid1.SelectedItem
                CurrentColumnHeader = col.Header.ToString
                CurrentColumnIndex = col.DisplayIndex
                currentRowIndex = DGrid1.Items.IndexOf(DGrid1.CurrentItem)
                Exit While
            End If
        End If
    End While
    If currentRowIndex = -1 OrElse CurrentColumnIndex = -1 OrElse CurrentColumnHeader = "" OrElse Myrow Is Nothing Then Exit Sub
    
         'code to consume the variables from here
    
    Dim strinwar As String = Myrow.Item("header name or index").ToString()