我有一个 DataGridView。右键单击 DataGridView 的第 4 列中的单元格时,我创建了一个 ContextMenuStrip。但是我被卡住了,因为在左键单击 ContextMenuStrip 菜单项时,我希望从右键单击的单元格中提取数据。
我想要的单元格是 ContextMenuStrip 的左上角,这正是我右键单击并指向我要获取数据的单元格的位置。 屏幕抓取只是不显示鼠标光标。
这是我到目前为止所拥有的:
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;
}
}
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;
}