C# - DatagridView and ContextMenuStrip

PATO7 picture PATO7 · Jul 22, 2011 · Viewed 9.3k times · Source

I have a datagridview with five columns and context menu strip which have items and sub items. When I right click on last column I want to open context menu.

I tried this code, but it's open context menu strip without sub items.

dataGrid.Columns[dataGrid.Columns.Count].HeaderCell.ContextMenuStrip = contextMenuStrip1;

Answer

Jay Riggs picture Jay Riggs · Jul 22, 2011

It looks like you want to open your ContextMenuStrip if your user right clicks the header of your DataGridView's last column. I would use the DataGridView MouseDown event and in that event check for these conditions and if they're met call the Show method of your ContextMenuStrip.

Like this:

private void dataGridView1_MouseDown(object sender, MouseEventArgs e) {
    if (e.Button == MouseButtons.Right) {
        var ht = dataGridView1.HitTest(e.X, e.Y);
        // See if the user right-clicked over the header of the last column.
        if ((    ht.ColumnIndex == dataGridView1.Columns.Count - 1) 
             && (ht.Type == DataGridViewHitTestType.ColumnHeader)) {
            // This positions the menu at the mouse's location.
            contextMenuStrip1.Show(MousePosition);
        }
    }
}