Home > Software engineering >  How to detect if a mouse event is on the row divider or on the row itself
How to detect if a mouse event is on the row divider or on the row itself

Time:10-20

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

CodePudding user response:

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 inside the client area (MouseEventArgs already returns Mouse coordinates relative to the Control's Client area).

If the Hit Test is successful, you can use the Hit Test's RowIndex 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

  • Related