How do I correctly position a Context Menu when I right click a DataGridView's column header?

前端 未结 9 993
名媛妹妹
名媛妹妹 2020-12-29 02:58

I would like to extended DataGridView to add a second ContextMenu which to select what columns are visible in the gird. The new ContextMenu will be displayed on right click

相关标签:
9条回答
  • 2020-12-29 03:04

    Here is a very simple way to make context menu appear where you right-click it.

    Handle the event ColumnHeaderMouseClick

    private void grid_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) 
    {
      if (e.Button == System.Windows.Forms.MouseButtons.Right)
        contextMenuHeader.Show(Cursor.Position);
    }
    

    contextMenuHeader is a ContextMenuStrip that can be defined in the Designer view or at runtime.

    0 讨论(0)
  • 2020-12-29 03:04

    To get the coordinate of the mouse cursor you could do this.

    ContextMenu.Show(this, myDataGridView.PointToClient(Cursor.Position)); 
    
    0 讨论(0)
  • 2020-12-29 03:11

    e.Location does not show the popup menu at the correct coordinates, instead just use the MousePosition property as follows:

    ContextMenuStrip.Show(MousePosition)
    

    or, explicitely

    ContextMenuStrip.Show(Control.MousePosition)
    
    0 讨论(0)
  • 2020-12-29 03:13

    Calling Show twice will get you the exact location of the cursor. This answer is for those whom are unable to get the result with all above answers.

    private void MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Right)
        {
            contextMenuStrip.Show(dataGrid, e.Location));
            contextMenuStrip.Show(Cursor.Position);
        }
    }
    
    0 讨论(0)
  • 2020-12-29 03:13

    Finally this worked for me.

    ContextMenu.Show(myDataGridView, myDataGridView.PointToClient(Cursor.Position)); 
    
    0 讨论(0)
  • 2020-12-29 03:17

    The position returned is relative to the cell. So we have to add that offset.

        private void grdView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                var pos = ((DataGridView)sender).GetCellDisplayRectangle(e.ColumnIndex, 
                e.RowIndex, false).Location;
                pos.X += e.X;
                pos.Y += e.Y;
                contextMenuStrip.Show((DataGridView)sender,pos);
            }
        }
    
    0 讨论(0)
提交回复
热议问题