gpt4 book ai didi

C# DataGridView 右键单击​​到 ContextMenu 单击检索单元格值

转载 作者:行者123 更新时间:2023-11-30 12:47:19 24 4
gpt4 key购买 nike

我有一个 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;
}

最佳答案

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

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

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

这样你就不会看到错误信息了,就可以按照你在帖子中看到的去做了。

关于C# DataGridView 右键单击​​到 ContextMenu 单击检索单元格值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17226253/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com