C#DataGridView右键单击ContextMenu单击“检索单元格值”
我有一个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开始,您不需要所有委托包装语法,您可以只是=与事件委托的签名匹配的函数,如下所示: // Your updated MouseDown handler function with DataGridViewCellMouseEventArgs GridView1.CellMouseDown += this.dataGridView_MouseDown; 然后您将没有错误消息,并且可以执行您在帖子中看到的内容. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |