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
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.
To get the coordinate of the mouse cursor you could do this.
ContextMenu.Show(this, myDataGridView.PointToClient(Cursor.Position));
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)
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);
}
}
Finally this worked for me.
ContextMenu.Show(myDataGridView, myDataGridView.PointToClient(Cursor.Position));
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);
}
}