Creating a Context Menu on a DataGridView Mouse

本文介绍了一种在DataGridView中为不同列动态创建上下文菜单的方法。通过定义特定于列的ContextMenu对象并根据鼠标右击的位置显示相应的菜单项,实现了灵活的用户交互。此方法适用于需要根据不同列提供不同操作的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

One of the projects had a requirement to create a context menu on mouse click over a DataGridView having employee details. The menu items may vary from column to column of the gridview.

//Define different context menus for different columns
private ContextMenu contextMenuForColumn1 = new ContextMenu();
private ContextMenu contextMenuForColumn2 = new ContextMenu();

Add the following line of code in the form load event:

private void Form_Load(object sender, EventArgs e)
{
    // Load all default values of controls
    populateDataGridView();

    // Add context mneu items
    contextMenuForColumn1.MenuItems.Add("Make Active", new     EventHandler(MakeActive));
    contextMenuForColumn2.MenuItems.Add("Delete", new     EventHandler(Delete));
    contextMenuForColumn2.MenuItems.Add("Register", new     EventHandler(Register));
}

Add the following code to mouseup event of the gridview:

private void dataGridView_MouseUp(object sender, MouseEventArgs e)
{
    // Load context menu on right mouse click
    DataGridView.HitTestInfo hitTestInfo;
    if (e.Button == MouseButtons.Right)
    {
        hitTestInfo = dataGridView.HitTest(e.X, e.Y);
        // If column is first column
        if (hitTestInfo.Type == DataGridViewHitTestType.Cell && hitTestInfo.ColumnIndex == 0)
            contextMenuForColumn1.Show(dataGridView, new Point(e.X, e.Y));
        // If column is second column
        if (hitTestInfo.Type == DataGridViewHitTestType.Cell && hitTestInfo.ColumnIndex == 1)
            contextMenuForColumn2.Show(dataGridView, new Point(e.X, e.Y));
    }
}

转载于:https://www.cnblogs.com/xiongeee/archive/2007/03/08/668051.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值