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;
}
}
}
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;
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)

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