Right now I've set up a ContextMenu on a datagridview. One of the options on the ContextMenu is to Edit the Cell that the person right clicked.
However I am unable to get the EventArgs or the Sender in the event handler to return which cell the user clicked on.
Is there any way to have the EventArgs return what would be found in something like DataGridViewCellMouseEventArgs??
So that I could do something like e.RowIndex to return which row the user clicked on??? OR does anyone have another solution??
Thanks
Loading
Ashley ArgilePosted Oct 10, 2008, 6:22 PM
Don't link the ContextMenuStrip to the DataGridView but handle the click event on the DataGridView and use it to show the menu. Pass the location from the MouseEventArgs in the menu show method to ensure that it appears underneath the mouse pointer. Before showing the menu store the MouseEventArgs so that you can use them in the handler for the menu items. In the menu item handler use the stored MouseEventArgs to generate HitTestInfo and use this to locate the cell that was right clicked. See below for the implementation.... Note it is important that you do not set the ContextMenuStrip property on the DataGridView or else the events will fire in the wrong order.
MouseEventArgs thisMouseEventArgs;
private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
thisMouseEventArgs = e;
contextMenuStrip1.Show(dataGridView1, e.X, e.Y);
}
}
private void toolStripMenuItem2ToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Windows.Forms.DataGridView.HitTestInfo hitTestInfo = dataGridView1.HitTest(thisMouseEventArgs.X, thisMouseEventArgs.Y);
if (hitTestInfo.Type == DataGridViewHitTestType.Cell)
{
MessageBox.Show("toolStripMenuItem2 : " + dataGridView1.Rows[hitTestInfo.RowIndex].Cells[hitTestInfo.ColumnIndex].Value);
}
}
private void toolStripMenuItem1ToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Windows.Forms.DataGridView.HitTestInfo hitTestInfo = dataGridView1.HitTest(thisMouseEventArgs.X, thisMouseEventArgs.Y);
if (hitTestInfo.Type == DataGridViewHitTestType.Cell)
{
MessageBox.Show("toolStripMenuItem1 : " + dataGridView1.Rows[hitTestInfo.RowIndex].Cells[hitTestInfo.ColumnIndex].Value);
}
}
Hope this help....
Regards
Ashley.
p.s.
If you need a sample I'm sure I can find a way to send it to you.
Chris GundersonPosted Oct 10, 2008, 5:00 PM