2017-08-08 69 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 
       } 
      } 
     }