V.V
V.V

Reputation: 883

How to show different contextmenustrip in datagridview using c#

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.

Upvotes: 1

Views: 1329

Answers (1)

Hans Passant
Hans Passant

Reputation: 942538

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);
    }

Upvotes: 2

Related Questions