I have a DataGridView. I created a ContextMenuStrip by directly clicking a cell in column 4 of my DataGridView. However, I am stuck because by left-clicking on the ContextMenuStrip menu item, I would like to extract data from the cell that was right-clicked.
I want the cell to be in the upper left corner of ContextMenuStrip, and that is where I right-clicked and pointed to the cell which data I want to capture. The capture screen simply does not show the mouse cursor.
This is what I have so far:
GridView1.MouseDown += new MouseEventHandler(this.dataGridView_MouseDown); private void dataGridView_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { var ht = dataGridView1.HitTest(eX, eY); //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'm looking for
However, if I change: private void dataGridView_MouseDown(object sender, MouseEventArgs e) to
private void dataGridView_MouseDown(object sender, DataGridViewCellMouseEventArgs e)
I'm not sure how to change GridView1.MouseDown += new MouseEventHandler(this.dataGridView_MouseDown); Therefore, I do not receive an error message. Or is there a better way to do this?
The Ultimate Solution Using 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; }
source share