9

I'm trying to open a contextmenustrip at the place where I right-clicked the mouse, but it always shows at top left of the screen.

Here is the code I used:

private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        contextMenuStrip1.Show(new Point(e.X,e.Y));
        doss.getdossier(connection.conn, Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value));
    }
}
JYelton
  • 35,664
  • 27
  • 132
  • 191
Tarik Mokafih
  • 1,247
  • 7
  • 19
  • 38

2 Answers2

12
if (e.Button == MouseButtons.Right)
{
    contextMenuStrip1.Show(Cursor.Position);
}

the reason it's not appearing is because you are using e.X and e.Y for the values. They are not the actual location on the screen. They are the location of the mouse within the datagrid. So say you clicked on the first cell of the first row, that will be near the top left of that component. e.X and e.Y are the mouse locations within the component.

Stuart Thomson
  • 509
  • 5
  • 21
2

assuming you are in Windows Forms, try this:

if (e.Button == MouseButtons.Right)
{
  Control control = (Control) sender;

  // Calculate the startPoint by using the PointToScreen 
  // method.

  var startPoint = control.PointToScreen(new Point(e.X, e.Y));
  contextMenuStrip1.Show(startPoint);
  ...
  ...
Davide Piras
  • 43,984
  • 10
  • 98
  • 147