如何使用c#在datagridview中显示不同的contextmenustrip [英] How to show different contextmenustrip in datagridview using c#

查看:124
本文介绍了如何使用c#在datagridview中显示不同的contextmenustrip的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我右键单击datagridview时,我需要显示contextmenustrip。我的问题是,如果我右键单击datagridview列标题,应该显示一种类型的菜单。如果我右键单击网格单元,则显示不同的菜单项。我已经使用标题栏鼠标单击和单元格鼠标单击。但是我遇到了一些问题。标题栏鼠标单击不起作用。请给出解决方案。

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.

推荐答案

只需使用MouseUp事件来检测鼠标单击。 DataGridView.HitTest()方法可以告诉您单击了DGV的哪一部分,从而允许您选择所需的CMS。例如:

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

这篇关于如何使用c#在datagridview中显示不同的contextmenustrip的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆