C# · 12月 26, 2021

C# – DatagridView和ContextMenu

我有一个datagridview,我显示关于产品的信息.我想绑定一个上下文菜单,当用户选择一个单元格,然后右键单击该单元格.我有另一个上下文菜单,并且绑定到datagridview的列.如果用户右键单击上下文菜单显示的列.

我已经尝试过这样但是不行.上下文菜单显示用户右键单击单元格,但是绑定到列标题的上下文菜单不起作用.

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

如何让用户右键点击datagridview显示?

提前多次.

编辑

Thnx为答案.我解决了这个问题:

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); } } }

上下文显示.当我点击上下文菜单显示的列,当我点击上下文菜单显示的单元格.

解决方法 尝试这个 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,e.Y)); }}