右键单击dataGridView而不选择行

时间:2017-08-08 08:38:29

标签: c# winforms datagridview contextmenu

有没有办法在contextmenu上显示DataGridView而不选择行?我希望通过选择行和不选择行来两种方式在contextmenu上显示DataGridView。以下是我在所选行上显示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);
        }
    }

1 个答案:

答案 0 :(得分:1)

如果这对你没有帮助,那就让我们编辑你的代码吧。

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
                }
            }
        }