2017-08-08 59 views
1

有没有什么办法可以在DataGridView上显示contextmenu而不选择行?我希望通过选择行和不选择行的方式,在DataGridView上显示contextmenu。这是我在选定的行上显示contextmenu的代码。在dataGridView中右键点击没有选择行

任何帮助将不胜感激。

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); 
     } 
    } 
+0

[为DataGridView的右键快捷菜单(https://stackoverflow.com/questions/1718389/right-click-context-menu-for-datagridview)的可能的复制 – Sahin

+1

_”有什么办法在DataGridView上显示contextmenu而不选择行?“_... yes ...使用'DataGridViews'' ContextMenuStrip'将允许用户右键单击网格以获得上下文菜单。右击网格将不会选择或取消选择任何单元格。 – JohnG

回答

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