5

I have a DataGridView with rows that I group based on group number. To visually separate the rows of different groups, I set the DividerHeight of the last row in a certain group.

I want to implement a different behaviour for mouse events for row dividers and the rows themselves. DataGridView.HitTestInfo doesn't seem to have a way of checking this. Is there any way for me to find out if a row divider was clicked or if anything was dropped on it?

An image of how my grid looks. (dark grey areas are the row dividers):

enter image description here

Tu deschizi eu inchid
  • 4,117
  • 3
  • 13
  • 24
denideni21
  • 53
  • 3

1 Answers1

3

The DataGridView HitTest() method returns information related to the Row at the specified client coordinates (coordinates relative to the DataGridView Client area).
You can use the MouseDown event of the DataGridView to determine the Mouse coordinates (MouseEventArgs already returns Mouse coordinates relative to the Control's Client area).

If the Hit Test is successful, you can use its RowIndex Property to determine the bounds of the Row under the Mouse Pointer, calling DataGridView.GetRowDisplayRectangle()

With this information, you can compare the position of the Mouse Pointer in relation to the bounds of the Row and the area occupied by the divider
The divider is part of the Row's bounding rectangle

Subtract the height of the divider ([Row].DividerHeight) from the [Row].Bounds.Bottom value and verify whether the Mouse Y position is greater than this value.

For example:

private void someDataGridView_MouseDown(object sender, MouseEventArgs e)
{
    var dgv = sender as DataGridView;
    var test = dgv.HitTest(e.X, e.Y);
    if (test.RowIndex == -1) return;

    var row = dgv.Rows[test.RowIndex];
    var rowBounds = dgv.GetRowDisplayRectangle(test.RowIndex, false);

    bool isDivider = e.Y >= (rowBounds.Bottom - row.DividerHeight);
}

Adapt as required in case custom painting is in place

Jimi
  • 29,621
  • 8
  • 43
  • 61
  • This worked perfectly, thank you! A side note for DataGridViewCellMouseEventArgs in the CellMouseClick event which might be useful for someone - the Y and X coordinates are local to the row rectangle, which means the Y-coordinate of the event arguments is in the range between 0 and the row's Height. – denideni21 Oct 20 '22 at 07:34
  • 1
    Sure. You can use that event anyway, though. `GetRowDisplayRectangle()` only needs the Row's Index and the Mouse coordinates are: `var pos = [DataGridView].PointToClient(MousePosition);` – Jimi Oct 20 '22 at 07:42