Jam*_*ole 2 c# datagridview contextmenu winforms
我已经寻找了很长一段时间,现在正在寻找一个可行的解决方案,但是我还是想问一个问题:
我的应用程序在对话框窗体中有一个DataGridView,我希望ContextMenu出现在单元格的右键单击上。
我单击鼠标右键,然后ContextMenu看起来很好,但是无论我尝试使用哪种解决方案在StackExchange上,它总是偏移很多。
这与表格和/或它的父母有关吗?还是我只是在这里愚蠢地错过了什么?
谢谢杰米
Form.cs
private void dataGridContents_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
if (e.RowIndex > -1 && e.ColumnIndex > -1)
{
Debug.WriteLine("Cell right clicked!");
DataGridViewCell cell = (sender as DataGridView)[e.ColumnIndex, e.RowIndex];
contextCell.Show(cell.DataGridView, PointToClient(Cursor.Position));
if (!cell.Selected)
{
cell.DataGridView.ClearSelection();
cell.DataGridView.CurrentCell = cell;
cell.Selected = true;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑
抱歉,我尝试过:
new Point(e.X, e.Y)new Point(e.Location.X, e.Location.Y)new Point(MousePosition.X, MousePosition.Y)PointToClient(e.X, e.Y)new Point(Cursor.Position.X, Cursor.Position.Y)Control.MousePositionCursor.Position可能还有其他一些。
编辑2
这就是我所说的偏移量-有些解决方案导致此偏移量在一定程度上发生变化(有些确实很远,等等)-但所有偏移量都与实际Cursor一样。
编辑3
我contextCell是一个new ContextMenu()
选项1:显示行的上下文菜单最简单的解决方案是将上下文菜单分配给RowTemplate.ContextMenuStripDataGridView的属性:
dataGridView1.RowTemplate.ContextMenuStrip = contextMenuStrip1;
Run Code Online (Sandbox Code Playgroud)
选项2:同样,如果您想在显示之前选择单元格ContextMenuStrip,则足以处理CellContextMenuStripNeeded事件:
private void dataGridView1_CellContextMenuStripNeeded(object sender,
DataGridViewCellContextMenuStripNeededEventArgs e)
{
if (e.RowIndex > -1 && e.ColumnIndex > -1)
{
dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
e.ContextMenuStrip = contextMenuStrip1;
}
}
Run Code Online (Sandbox Code Playgroud)
你怎么了
您正在DataGridView错误地计算鼠标在上的位置。您正在使用PointToClient哪种方法this.PointToClient,而您需要使用的方法DataGridView,例如dataGridView1.PointToClient:
myContextMenu.Show(dataGridView1,dataGridView1.PointToClient(Cursor.Position));
Run Code Online (Sandbox Code Playgroud)
仅出于您的参考,您可以简单地ContextMenu使用此代码进行演示,而无需使用ContextMenuStrip。
但我强烈建议您使用ContextMenuStrip。