在不选择行的情况下右键单击 dataGridView

Right click in dataGridView without selecting row

有没有办法在不选择行的情况下在 DataGridView 上显示 contextmenu?我希望通过选择行和不选择行两种方式在 DataGridView 上显示 contextmenu。这是我在选定行上显示 contextmenu 的代码。

如有任何帮助,我们将不胜感激。

private void ProductServicesDataGrid_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Right)
        {
            var hti = ProductServicesDataGrid.HitTest(e.X, e.Y);
            ProductServicesDataGrid.Rows[hti.RowIndex].Selected = true;

            ProductContextMenu.Show(ProductServicesDataGrid, e.X, e.Y);
        }
    }

如果这对您没有帮助,让我们稍微修改一下您的代码。

private void ProductServicesDataGrid_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                 if(ProductServicesDataGrid.SelectedCells!=null)
                 {
                  // you can use selected rows in a foreach loop however you want                         
                 ProductContextMenu = new ProductContextMenu();
                     foreach (DataGridViewCell cell in ProductServicesDataGrid.SelectedCells)
                      {
                      m.MenuItems.Add(new MenuItem(cell.Value));
                      }
                      ProductContextMenu.Show(ProductServicesDataGrid, e.X, e.Y);
                 }
                else 
                {
                 // any cells are selected
                }
            }
        }