I need to programmatically show the context menu for a grid, but my logic isn't working.
I have defined a MouseDown event for the grid in order to disambiguate the click and double-click events if the left button is clicked. If the right button is clicked I perform the following logic, but nothing happens:
if (sender is UltraGrid){ UltraGrid grid = (UltraGrid)sender; if (grid.ContextMenu.SourceControl != null) { // X & Y values are from the MouseDown event Point point = new Point(e.X, e.Y); // The grid context control is a ContexMenuStrip control which worked correctly prior to the MouseDown implementation grid.ContextMenu.Show(grid.ContextMenu.SourceControl, point); }}
What is wrong with the code?
BTW,I also tried moving this code to the MouseUp event.
The logic is called and executed, but again, nothing happens.
Hi Richard,
How did you assign your ContextMenu to the grid? Are you using the inbox ContextMenu or ContextMenuStrip? Or are you using UltraToolbarsManager?
Yes - the context menu has been assigned to the grid, and I am using ContextMenuStrip control.
But I should provide the routine I am using to create the content menu. I call it with a ContextMenuStrip control, but it actually loads a ContextMenu, as follows:
public static void SetGridContextMenu(UltraGrid grid, ContextMenuStrip menuStrip, params EventHandler[] events) { try { if (grid == null) return;
if (grid.ContextMenu == null) grid.ContextMenu = new ContextMenu(); else grid.ContextMenu.MenuItems.Clear();
if (menuStrip.Items.Count != events.Length) // Make sure that there are the same number of event handlers as menu items return;
// Set the grid context menu from a context menu strip defined on the form for (int index = 0; index < menuStrip.Items.Count; index++) { MenuItem item = new MenuItem(menuStrip.Items[index].Text); // The tag must be set according to the action type of the menu item "Add", "Del", or "Upd" item.Tag = menuStrip.Items[index].Tag; grid.ContextMenu.MenuItems.Add(item); item.Click += new EventHandler(events[index]); } } catch { } }
Hello Richard,
If you are using a ContextMenuStrip you are going to eventually want to call grid.ContextMenuStrip.Show instead of calling ContextMenu.
I attached a sample sample that demonstrates this working. Let me know if you have any questions. If you happen to still find issues please modify my sample so we can investigate it further. Thanks.
DO you have any VB.net examples of this?
I added a VB version of the sample into the solution.
GridContextMenuSample.zip