Revision: 9393
Updated Code
at November 3, 2008 14:02 by pckujawa
Updated Code
/// <summary> /// Copy selected item from DGV. /// </summary> /// <param name="sender">A ToolStripDropDownItem</param> /// <param name="e"></param> private void copyToolStripMenuItem_Click(object sender, EventArgs e) { // The context menu strip called this method, so we need to determine which DGV it was clicked on { ToolStripDropDownItem item = sender as ToolStripDropDownItem; if (item == null) // Error return; ContextMenuStrip strip = item.Owner as ContextMenuStrip; grid = strip.SourceControl as DataGridView; } if (grid == null) // Control wasn't a DGV return; DataObject data = grid.GetClipboardContent(); Clipboard.SetDataObject(data); }
Revision: 9392
Initial Code
Initial URL
Initial Description
Initial Title
Initial Tags
Initial Language
at November 3, 2008 14:00 by pckujawa
Initial Code
/// <summary> /// Copy selected item from DGV. /// </summary> /// <param name="sender">A ToolStripDropDownItem</param> /// <param name="e"></param> private void copyToolStripMenuItem_Click(object sender, EventArgs e) { // The context menu strip called this method, so we need to determine which DGV it was clicked on { ToolStripDropDownItem item = sender as ToolStripDropDownItem; if (item == null) // Error return; ContextMenuStrip strip = item.Owner as ContextMenuStrip; grid = strip.SourceControl as DataGridView; } DataObject data = grid.GetClipboardContent(); Clipboard.SetDataObject(data); }
Initial URL
Initial Description
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.
Initial Title
How to tell what form control a context menu was over when you clicked one of its items
Initial Tags
forms
Initial Language
C#