鼠标右键单击contextMenuStrip第一次不显示

时间:2013-12-25 16:17:13

标签: c# datagridview mouseevent contextmenustrip

我得到了这部分代码,我打开了contextMenuStrip以响应鼠标右键单击(通过dataGridView表)。

问题是,我第一次点击右键 - 菜单没有弹出。第二次弹出,从那以后一切运行良好..

    private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
    {
        DataGridView.HitTestInfo info = dataGridView1.HitTest(e.X, e.Y); //get info
        int currentMouseOverRow = dataGridView1.HitTest(e.X, e.Y).RowIndex;

        if (e.Button == MouseButtons.Right) //MouseButton right: Open context menu strip.
         {
             dataGridView1.Rows[currentMouseOverRow].Selected = true; //Select the row

             ContextMenuStrip Menu = new ContextMenuStrip();
             ToolStripMenuItem MenuOpenPO = new ToolStripMenuItem("Delete it");
             MenuOpenPO.Click += new EventHandler(MenuOpenPO_Click);
             Menu.Items.AddRange(new ToolStripItem[] { MenuOpenPO });
             dataGridView1.ContextMenuStrip = Menu; //Assign to dataGridView1
         }
    }

有任何帮助吗? :)我使用visual studio 2012。

2 个答案:

答案 0 :(得分:4)

问题:您在ContextMenu事件后DataGridView添加了RightClick。因此ContextMenu会在第一个DataGridView之后添加到RightClick,因此用户可以看到其他ContextMenu事件中附加的RightClick

解决方案:在右键点击ContextMenu之前,您需要添加DataGridView,以便每个RightClick事件都会显示。{/ p >

注意:如果将ContextMenu分配给任何控件,默认情况下它将显示在rightclick上,表示您不需要为每个{{1}添加RightClick显式控件上的事件。

试试这个:Form Load事件

   private void Form1_Load(object sender, EventArgs e)
    {
        dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        ContextMenuStrip Menu = new ContextMenuStrip();
        ToolStripMenuItem MenuOpenPO = new ToolStripMenuItem("Delete it");
        MenuOpenPO.Click += new EventHandler(MenuOpenPO_Click);
        Menu.Items.AddRange(new ToolStripItem[] { MenuOpenPO });
        dataGridView1.ContextMenuStrip = Menu; //Assign to dataGridView1
    }

答案 1 :(得分:1)

我通常会在需要时创建自己的ContextMenuStrip对象(私有变量)和Show()对象。我怀疑它是第一次分配,但无法显示,因为新添加的菜单没有自己的右键单击触发器来显示。只有在第二次存在时才会发生这种情况。

像这样:     private ContextMenuStrip _myMenu;

private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
    DataGridView.HitTestInfo info = dataGridView1.HitTest(e.X, e.Y); //get info
    int currentMouseOverRow = dataGridView1.HitTest(e.X, e.Y).RowIndex;

    if (e.Button == MouseButtons.Right) //MouseButton right: Open context menu strip.
     {
         dataGridView1.Rows[currentMouseOverRow].Selected = true; //Select the row

         _myMenu = new ContextMenuStrip();
         ToolStripMenuItem MenuOpenPO = new ToolStripMenuItem("Delete it");
         MenuOpenPO.Click += new EventHandler(MenuOpenPO_Click);
         _myMenu.Items.AddRange(new ToolStripItem[] { MenuOpenPO });
         _myMenu.Show(new Point(e.X, e.Y));
     }
}