![](/img/trans.png)
[英]C# DataGridView Right Click to ContextMenu Click Retrieve Cell Value
[英]C# DataGridView opening ContextMenu at location of Right Click
我已經尋找了很長一段時間,現在正在尋找一個可行的解決方案,但是我還是想問一個問題:
我的應用程序在對話框窗體中有一個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;
}
}
}
}
編輯
抱歉,我嘗試過:
new Point(eX, eY)
new Point(e.Location.X, e.Location.Y)
new Point(MousePosition.X, MousePosition.Y)
PointToClient(eX, eY)
new Point(Cursor.Position.X, Cursor.Position.Y)
Control.MousePosition
Cursor.Position
可能還有其他一些。
編輯2
這就是我所說的偏移量-有些解決方案導致此偏移量在一定程度上發生變化(有些確實很遠,等等)-但所有偏移量都與實際Cursor一樣。
編輯3
我的contextCell
是一個new ContextMenu()
選項1:顯示行的上下文菜單的最簡單解決方案是將上下文菜單分配給DataGridView的RowTemplate.ContextMenuStrip
屬性:
dataGridView1.RowTemplate.ContextMenuStrip = contextMenuStrip1;
選項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;
}
}
你怎么了
您正在錯誤地計算鼠標在DataGridView
上的位置。 您正在使用PointToClient
,這意味着this.PointToClient
,而您需要使用DataGridView
的方法,例如dataGridView1.PointToClient
:
myContextMenu.Show(dataGridView1,dataGridView1.PointToClient(Cursor.Position));
僅作為參考,您可以使用此代碼簡單地顯示ContextMenu
而無需使用ContextMenuStrip
。
但我強烈建議您使用ContextMenuStrip
。
要么
this.dataGridView1.ContextMenuStrip = this.contextMenuStrip1;
並處理DataGridView.CellContextMenuStripNeeded
事件
答案是使contextCell
成為ContextMenuStrip
而不是原來的ContextMenu
。
畢竟........
感謝您的回復。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.