How to identify dataGridView cell that was right clicked on for ContextMenuStrip?

吃可爱长大的小学妹 提交于 2019-12-05 15:13:47

You could keep track of whichever cell was last clicked by adding an event handler for the DataGridView's mouse click.

Something like:

    DataGridViewCell clickedCell;

    private void dataGridView1_CellMouseClick_1(object sender, DataGridViewCellMouseEventArgs e)
{
        try
    {
        DataGridView view = (DataGridView)sender;

        if (e.Button == System.Windows.Forms.MouseButtons.Right && e.RowIndex >= 0)
        {
            Console.WriteLine("Clicked column " 
                       + e.ColumnIndex + ", row " 
                       + e.RowIndex + " of DataGridView " 
                       + view.Name + " at " 
                       + System.Windows.Forms.Cursor.Position);

           clickedCell = view.Rows[e.RowIndex].Cells[e.ColumnIndex];
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace);
    }
}

Then in your contextMenuStripItem click event, switch on clickedCell.Value like:

switch (clickedCell.Value)
        {
            case "Copy":
            break;
... // etc.
}

You can do this using a HitTest with the datagridview.

This is an example of code that I have used.

        DataGridView dgv= (DataGridView)sender;
        if (e.Button == System.Windows.Forms.MouseButtons.Right)
        {
            try
            {
                dgv.CurrentCell = dgv[gvw.HitTest(e.X, e.Y).ColumnIndex, dgv.HitTest(e.X, e.Y).RowIndex];
            }
        }

You can then use the DGV.CurrentCell to find all the information.

switch ""
{
    case ""
      break;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!