1

Is there any way to show contextmenu on DataGridView without selecting row? I want both ways to show contextmenu on DataGridView by selecting row and by not selecting row. Here is my code for showing contextmenu on selected row.

Any help would be much appreciated.

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);
        }
    }
Hammad Ahmed
  • 60
  • 2
  • 9
  • Possible duplicate of [right click context menu for datagridview](https://stackoverflow.com/questions/1718389/right-click-context-menu-for-datagridview) – Sahin Aug 08 '17 at 08:48
  • 1
    _”Is there any way to show contextmenu on DataGridView without selecting row?”_... yes… using the `DataGridViews` `ContextMenuStrip` will allow the user to right-click on the grid to get a context menu. Right-clicking into the grid will not select or deselect any cells. – JohnG Aug 08 '17 at 09:59

1 Answers1

1

If that didn't help you, let's edit your code a little bit.

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
                }
            }
        }
Sahin
  • 114
  • 7