日期:2014-05-18  浏览次数:20883 次

如何让菜单弹出在鼠标所点位置
在dataGridView中点右键弹出菜单,菜单位置怎么控制?
我的dataGridView的选中方式为:FullRowsSelect
程序为:
private void dataGridView_CellMouseDown(object sender,DataGridViewCellMouseEventArgs e)
{
  if(e.button==MouseButton.Right && e.ColumnIndex > -1 && e.RowIndex > -1)
  {
  dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Select=true;
   
  ContextMenu con = new ContextMenu ();
  MenuItem Add_user = new MenuItem Add_user ("添加");
  MenuItem menuLine1_user= new MenuItem ("_");
  MenuItem Update_user = new MenuItem Add_user ("修改");
  MenuItem menuLine2_user= new MenuItem ("_");
  MenuItem Delete_user = new MenuItem Add_user ("删除");

  Add_user.Click += new EventHandler(this.Add_user_click_ToolStripMenuItem_Click);
  Update_user.Click += new EventHandler(this.Update_user_click_ToolStripMenuItem_Click);
  Delete_user.Click += new EventHandler(this.Delete_user_click_ToolStripMenuItem_Click);


  con.MenuItems.Add(Add_user);
  con.MenuItems.Add(menuLine1_user);
  con.MenuItems.Add(Update_user);
  con.MenuItems.Add(menuLine2_user);
  con.MenuItems.Add(Delete_user);

   
  this.dataGridView.ContextMenu = con;
  con.Show(dataGridView,new point(e.X,e.Y));//就是这句,菜单都是乱蹦的!怎么控制啊?





   



  }
}

------解决方案--------------------
用ContextMenuStrip不好么,菜单弹出位置都设定好的
------解决方案--------------------
ContextMenuStrip
------解决方案--------------------
何必设定?多此一举,本来就是在鼠标旁出现的。
------解决方案--------------------
你想让菜单随着鼠标动?
------解决方案--------------------

用ContextMenuStrip控件 ,

C# code


  private void dgvList_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (e.RowIndex >= 0)
                {

                    if (dgvList.Rows[e.RowIndex].Selected == false)
                    {
                        dgvList.ClearSelection();
                        dgvList.Rows[e.RowIndex].Selected = true;
                    }
                    if (dgvList.SelectedRows.Count == 1 && e.ColumnIndex != -1)
                    {
                        dgvList.CurrentCell = dgvList.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    }
                    dgvList.ContextMenuStrip = contextMenuStrip1;
                }

                else
                {
                    dgvList.ContextMenuStrip = null;
                    return;
                }
            }
        }