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

前端 未结 9 1028
名媛妹妹
名媛妹妹 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条回答
  •  梦毁少年i
    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);
            }
        }
    

提交回复
热议问题