C#DataGridView右键单击ContextMenu单击“检索单元格值”

时间:2013-06-21 01:11:46

标签: c# datagridview contextmenustrip

我有一个DataGridView。在右键单击DataGridView的第4列中的单元格时,我创建了一个ContextMenuStrip。但是我被卡住了,因为在左键单击ContextMenuStrip菜单项我希望从右键单击的单元格中提取数据。

我想要的单元格是ContextMenuStrip的左上角,这正是我右键单击的位置,并指向我想要抓取的数据的单元格。 The screen grab just doesn't show the mouse cursor.

这是我到目前为止所做的:

GridView1.MouseDown += new MouseEventHandler(this.dataGridView_MouseDown);

private void dataGridView_MouseDown(object sender, MouseEventArgs e)
    {

        if (e.Button == MouseButtons.Right)
        {
            var ht = dataGridView1.HitTest(e.X, e.Y);

            //Checks for correct column index
            if (ht.ColumnIndex == 4 && ht.RowIndex != -1)
            {
                //Create the ContextStripMenu for Creating the PO Sub Form
                ContextMenuStrip Menu = new ContextMenuStrip();
                ToolStripMenuItem MenuOpenPO = new ToolStripMenuItem("Open PO");
                MenuOpenPO.MouseDown += new MouseEventHandler(MenuOpenPO_Click);
                Menu.Items.AddRange(new ToolStripItem[] { MenuOpenPO });

                //Assign created context menu strip to the DataGridView
                dataGridView1.ContextMenuStrip = Menu;
            }

            else
                dataGridView1.ContextMenuStrip = null;
        }
    }

I think this post may be what I am looking for

但是,如果我改变:private void dataGridView_MouseDown(object sender, MouseEventArgs e)

private void dataGridView_MouseDown(object sender, DataGridViewCellMouseEventArgs e)

我不确定如何更改GridView1.MouseDown += new MouseEventHandler(this.dataGridView_MouseDown);因此我没有收到错误消息。或者有更好的方法吗?

最终解决方案 在Gjeltema的帮助下

dataGridView1.CellMouseDown += this.dataGridView1_CellMouseDown;

    private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
    {
        //Checks for correct column index
        if (e.Button == MouseButtons.Right && e.ColumnIndex == 4 && e.RowIndex != -1)
        {
            //Create the ContextStripMenu for Creating the PO Sub Form
            ContextMenuStrip Menu = new ContextMenuStrip();
            ToolStripMenuItem MenuOpenPO = new ToolStripMenuItem("Open PO");
            MenuOpenPO.MouseDown += new MouseEventHandler(MenuOpenPO_Click);
            Menu.Items.AddRange(new ToolStripItem[] { MenuOpenPO });

            //Assign created context menu strip to the DataGridView
            dataGridView1.ContextMenuStrip = Menu;
            CellValue = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
        }

        else
            dataGridView1.ContextMenuStrip = null;
    }

1 个答案:

答案 0 :(得分:1)

如果你正在使用该帖子的解决方案,请注意他正在订阅CellMouseDown事件,而不是MouseDown事件。这有不同的签名。

此外,从.Net 2.0开始,您不需要所有委托包装语法,只需+=匹配事件委托签名的函数,如下所示:

// Your updated MouseDown handler function with DataGridViewCellMouseEventArgs
GridView1.CellMouseDown += this.dataGridView_MouseDown;

然后您将没有错误消息,并且可以执行您在帖子中看到的内容。