【问题标题】:C# - DatagridView and ContextMenuC# - DatagridView 和 ContextMenu
【发布时间】:2011-05-04 14:09:43
【问题描述】:

我有一个数据网格视图,我在其中显示有关产品的信息。当用户选择一个单元格然后右键单击该单元格时,我想绑定一个上下文菜单。我有另一个上下文菜单,它绑定到 datagridview 的列。如果用户右键单击列,则会显示上下文菜单。

我试过这样,但它不起作用。当用户右键单击单元格时,上下文菜单会显示,但绑定到列标题的上下文菜单不起作用。

   private void GridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            productContextMenu.Show(GridView1, e.Location);
        }

    }

如何做到让用户右击datagridview时显示出来?

提前感谢。

编辑

谢谢你的答案。我解决了这样的问题:

    private void GridView1_MouseUp(object sender, MouseEventArgs e)
    {
        DataGridView.HitTestInfo hitTestInfo;
        if (e.Button == MouseButtons.Right)
        {
            hitTestInfo = GridView1.HitTest(e.X, e.Y);
            if (hitTestInfo.Type == DataGridViewHitTestType.Cell)
            {
                productContextMenu.Show(GridView1, e.Location);
            }

        }
    }

两个上下文菜单都显示。当我单击上下文菜单显示的列时,以及单击上下文菜单显示的单元格时。

【问题讨论】:

  • 感谢您知道您得到了答复 :)
  • 如果你得到了他的想法的解决方案,你为什么不标记为答案

标签: c# datagridview contextmenu


【解决方案1】:

试试这个

 private void dataGridView1_CellMouseDown(object sender, MouseEventArgs e)
{
  if (e.Button == MouseButtons.Right)
  {
        contextMenu.Show(datagridview, e.Location);
  }

} 

 private void dataGridView_MouseUp(object sender, MouseEventArgs e)
 {
   // Load context menu on right mouse click
   DataGridView.HitTestInfo hitTestInfo;
   if (e.Button == MouseButtons.Right)
   {
      hitTestInfo = dataGridView.HitTest(e.X, e.Y);
      // If column is first column
      if (hitTestInfo.Type == DataGridViewHitTestType.Cell && hitTestInfo.ColumnIndex == 0)
        contextMenuForColumn1.Show(dataGridView, new Point(e.X, e.Y));
    // If column is second column
      if (hitTestInfo.Type == DataGridViewHitTestType.Cell && hitTestInfo.ColumnIndex == 1)
        contextMenuForColumn2.Show(dataGridView, new Point(e.X, e.Y));
   }
} 

【讨论】:

  • 我不知道为什么,但它不起作用。当我右键单击 datagridview 列时,上下文菜单会显示,但是当我右键单击单元格时,上下文菜单不起作用。
  • 出于某种原因,我总是得到 hitTest.ColumnIndex 的第 0 列。这是我添加侦听器的代码:dataGridView.ColumnHeaderMouseClick += dataGridView_ColumnHeaderMouseClick; 这是我的侦听器定义:private void dataGridView_ColumnHeaderMouseClick(object sender, MouseEventArgs e)
【解决方案2】:

对于相对位置的问题,也可以使用这种方法:

DataGridViewColumn dgvC = new DataGridViewColumn();
DataGridViewRow dgvR = new DataGridViewRow();
dgvC = dgv.Columns[e.ColumnIndex];
dgvR = dgv.Rows[e.RowIndex];
Point p = new Point();
p.X = (dgvC.Width * e.ColumnIndex) + e.X;
p.Y = (dgvR.Height * e.RowIndex) + e.Y;
dgv.ContextMenu.Show(dgv, p);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多