Jevon Jevon - 9 days ago 5
C# Question

copy paste and cut clicks do not exist in current context

Am creating a context menu programmatically as to have right click options on my datagrid. Here is my code:

public partial class Form1 : Form
{
//string fileExcel;
public Form1()
{
InitializeComponent();
fillCari();
FillCombo();
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;


}


This particular block I keep getting the error that it does not exist in current context. Any idea why?

mnuCopy.Click += new EventHandler(mnuCopy_Click);
mnuCut.Click += new EventHandler(mnuCut_Click);
mnuPaste.Click += new EventHandler(mnuPaste_Click);


Updated question:I created the strips from the context menu but not sur ehow to implement the copy commands.

public partial class Form1 : Form
{
//string fileExcel;
public Form1()
{
InitializeComponent();
fillCari();
FillCombo();
ContextMenuStrip mnu = new ContextMenuStrip();
dataGridView3.ContextMenuStrip = mnu;
}


private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{

}

private void cutToolStripMenuItem_Click(object sender, EventArgs e)
{

}

private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{

}

Answer

I had figured it out for awhile now. Hopefully it helps anyone in the future. Keep in mind after creating your contextMenuStrip and adding a "copy" field to the strip you will then bind it to the dataGridView. This is done by going into properties of the context menu and looking for the dataGridView name and bind it to it. After that open the click event in properties on the contextMenu and add this code in it:

 private void copyToolStripMenuItem_Click(object sender, EventArgs e)
    {
        dataGridView3.Select();
        DataObject o = dataGridView3.GetClipboardContent();
        Clipboard.SetDataObject(o);
    }

You should now have your right click copy button working.

Comments