Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datagridview context menu always shows -1 in hittest

I am trying to create a context menu for a datagridview. I had tried a few samples from here but not able to understand why the below always returns -1 for any row clicked. This is a winforms and the grid is populated from a datatable. What am I doing wrong here?

 DataGridView.HitTestInfo hit = dgvResults.HitTest(e.X, e.Y);

My code:

private void dgvResults_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
  if (e.ColumnIndex >= 0 && e.RowIndex >= 0 && e.Button == MouseButtons.Right)
  {
      DataGridView.HitTestInfo hit = dgvResults.HitTest(e.X, e.Y); \\ this shows as -1 always
      if (hit.Type == DataGridViewHitTestType.Cell)
      {
         dgvResults.CurrentCell = dgvResults[hit.ColumnIndex, hit.RowIndex];
         cmsResults.Show(dgvResults, e.X, e.Y);
      }
  }
}

When I use the MouseClick event it seem to work, I a bit lost here

private void dgvResults_MouseClick(object sender, MouseEventArgs e)
{
  if (e.Button == MouseButtons.Right)
  {
    int currentMouseOverRow = dgvResults.HitTest(e.X, e.Y).RowIndex;
    cmsResults.Show(dgvResults, new Point(e.X, e.Y));

  }
}

Edit:

I finally got it to work with the below code.

Thanks to everyone

Code that worked for me:

private void dgvResults_MouseClick(object sender, MouseEventArgs e)
{
  if (e.Button == MouseButtons.Right)
   {
      int currentMouseOverRow = dgvResults.HitTest(e.X, e.Y).RowIndex;
      dgvResults.ClearSelection();
      if (currentMouseOverRow >= 0) // will show Context Menu Strip if not negative
      {
          dgvResults.Rows[currentMouseOverRow].Selected = true;
          cmsResults.Show(dgvResults, new Point(e.X, e.Y));
           row = currentMouseOverRow;
       }
   }
}
like image 523
Adrian Avatar asked Nov 16 '25 17:11

Adrian


2 Answers

Look at -

http://bytes.com/topic/c-sharp/answers/826824-invalid-coordinates-datagridview-hittest

In particular -

Point p = dataGridView2.PointToClient(new Point(e.X, e.Y);
DataGridView.HitTestInfo info = dataGridView2.HitTest(p.X, p.Y);
int row = info.RowIndex;
like image 108
Mike Avatar answered Nov 19 '25 09:11

Mike


This is normal behaviour as X and Y coordinates returned by EventArgs are relative to top left corner of hosting control:

  • MouseEventArgs return X/Y coordinates relative to DataGridView control.
  • DataGridViewCellMouseEventArgs return X/Y coordinates relative to DataGridViewCell control.

HitTest is performed against DataGridView control and just converts provided X/Y to Column/Row Indexes without any modifications.

Illustration below demonstrates the idea (with Blue - values returned by MouseEventArgs, with Green - by DataGridViewCellMouseEventArgs)

enter image description here

like image 23
Nogard Avatar answered Nov 19 '25 08:11

Nogard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!