11

I have a DataGridView (dgv1) on my form. In a particular cell, I'd like for the user to be able to right-click and choose "COPY" to copy the contents of the cell to the clipboard. Can anyone point me in the direction of a tutorial or site that shows how to accomplish this in C#?

Thanks!

Kevin
  • 4,798
  • 19
  • 73
  • 120

2 Answers2

19

You can use ContextMenuStrip to accomplish this. (Or ContextMenu for pre-VS2k5)

Excerpt from this article:

ContextMenuStrip mnu = new ContextMenuStrip();
ToolStripMenuItem mnuCopy = new ToolStripMenuItem("Copy");
ToolStripMenuItem mnuCut = new ToolStripMenuItem("Cut");
ToolStripMenuItem mnuPaste = new ToolStripMenuItem("Paste");
//Assign event handlers
mnuCopy.Click += new EventHandler(mnuCopy_Click);
mnuCut.Click += new EventHandler(mnuCut_Click);
mnuPaste.Click += new EventHandler(mnuPaste_Click);
//Add to main context menu
mnu.Items.AddRange(new ToolStripItem[] { mnuCopy, mnuCut, mnuPaste});
//Assign to datagridview
dataGridView1.ContextMenuStrip = mnu;

There is more information on the above link.

Kash
  • 8,799
  • 4
  • 29
  • 48
  • Only this was missing from the answer(but is in the provided link): private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) { row = e.RowIndex; col = e.ColumnIndex; } – Randall Flagg Jun 08 '17 at 04:40
2

You might want to create a contextmenustrip for the COPY option when you right click.

And in the datagridview properties in the rightclick eventhandler, you link this contextmenustrip.

And on clicking copy, you have another function where you say Clipboard.settext(Datagriditem.value)

This link should help you figure out how to get the right click menu.

right click context menu for datagridview

And use the Clipboard.Setdataobject to get the data into clipboard.

Community
  • 1
  • 1
roymustang86
  • 8,054
  • 22
  • 70
  • 101
  • 1
    Out of interest why was this set as the answer, I just thought @Kashinath Shenoy giving a code example was nice? – Paul C Aug 25 '11 at 09:37
  • Whoops! You are correct! I actually thought that I had chosen Kashinath's answer. Apparently, I clicked the wrong answer. I did end up using Kashinath's example in my code. – Kevin Aug 25 '11 at 20:32