How to tell what form control a context menu was over when you clicked one of its items


/ Published in: C#
Save to your folder(s)

If you add a ContextMenuStrip (the menu that shows up when you right-click on something) to your design, you can conveniently have more than one form control use that context menu. The only problem is that you don't know which control the context menu was over (in other words, what data the user right-clicked on) when you get the event for one of the ToolStripMenuItems on the ContextMenuStrip being clicked. Many others have monitored the control for mouse click events to tell which control fired the event, but I've found a better, more abstract way of determining this information.

In my case, I have two DataGridViews with the same context menu. The only items on that menu are Copy and Paste. The code below shows that, when Copy is clicked, the "sender" argument can be cast as a ToolStripDropDownItem, the Owner of which is a ContextMenuStrip. This Owner can be cast as the control which holds the data that the user clicked on, e.g. a DataGridView as in my case. From that point, the control can be manipulated in any way necessary.

I still haven't found a good way to have right-click select the item (cell, row, column, table) in the DGV as if the user left-clicked. Currently, the user needs to select the data with left-clicks and then right-click inside the DGV for the context-menu to know what data to use.


Copy this code and paste it in your HTML
  1. /// <summary>
  2. /// Copy selected item from DGV.
  3. /// </summary>
  4. /// <param name="sender">A ToolStripDropDownItem</param>
  5. /// <param name="e"></param>
  6. private void copyToolStripMenuItem_Click(object sender, EventArgs e)
  7. {
  8. // The context menu strip called this method, so we need to determine which DGV it was clicked on
  9. {
  10. ToolStripDropDownItem item = sender as ToolStripDropDownItem;
  11. if (item == null) // Error
  12. return;
  13. ContextMenuStrip strip = item.Owner as ContextMenuStrip;
  14. grid = strip.SourceControl as DataGridView;
  15. }
  16. if (grid == null) // Control wasn't a DGV
  17. return;
  18. DataObject data = grid.GetClipboardContent();
  19. Clipboard.SetDataObject(data);
  20. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.