当前上下文中不存在复制粘贴和剪切点击

时间:2016-11-18 14:29:40

标签: c# winforms

以编程方式创建上下文菜单,以便在我的数据网格上有右键单击选项。这是我的代码:

    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;


    }

这个特殊的块我不断得到它在当前上下文中不存在的错误。知道为什么吗?

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

更新的问题:我从上下文菜单中创建了条带,但没有实现复制命令。

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)
    {

    }

2 个答案:

答案 0 :(得分:1)

我现在已经想了一会儿。希望它能在未来帮助任何人。在创建contextMenuStrip并向条带添加“copy”字段后,请记住,然后将其绑定到dataGridView。这是通过进入上下文菜单的属性并查找dataGridView名称并将其绑定到它来完成的。之后,在contextMenu的属性中打开click事件,并在其中添加此代码:

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

您现在应该可以使用右键单击复制按钮。

答案 1 :(得分:0)

  

对于click事件,您需要事件处理程序:

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

  // event handler method
  void mnuPaste_Click(object sender, EventArgs e) {
    // paste logic
  }
  void mnuCut_Click(object sender, EventArgs e) {
    // cut logic
  }
  void mnuCopy_Click(object sender, EventArgs e) {
    // copy logic
  }