1
votes

I need show contextmenustrip when i right click on datagridview. My problem is, if i right click on datagridview column header one type of menu should show. If i right click on grid cells, show different menu items. I have used header column mouse click and cell mouse click. But i got some issue. Header column mouse click not working. Please give the solution.

1
What do you mean with "not working" and "some issues"? more details and code you triel could help. - Sefa
You can set the contextmenustrip using this: dataGridView1.Columns[0].HeaderCell.ContextMenuStrip for the header and and set one for grid. - danish

1 Answers

2
votes

Simply use the MouseUp event to detect the mouse click. The DataGridView.HitTest() method can tell you what part of the DGV was clicked, allowing you to pick the CMS you want. For example:

    private void dataGridView1_MouseUp(object sender, MouseEventArgs e) {
        if (e.Button != MouseButtons.Right) return;
        var dgv = (DataGridView)sender;
        ContextMenuStrip cms = null;
        var hit = dgv.HitTest(e.X, e.Y);
        switch (hit.Type) {
            case DataGridViewHitTestType.ColumnHeader: cms = contextMenuStrip1; break;
            case DataGridViewHitTestType.Cell: cms = contextMenuStrip2; break;
        }
        if (cms != null) cms.Show(dgv, e.Location);
    }