我試圖在上下文菜單上獲取單擊的項目。我從網上找到以下代碼,但我對ToolStripMenu
,ContextMenu
和MenuItem
有點困惑。從我可以找到這似乎是獲得選定的菜單項的正確方法,但它似乎並不適用於我。無法將ToolStripItem強制轉換爲MenuItem
右鍵單擊DataGrid
行時,我創建了一個上下文菜單。
在點擊事件中,我將發件人投給了MenuItem
。在調試器中,發件人對兩個項目看起來不錯,但var mi = sender as MenuItem
只返回null。請問我做錯了什麼?
ContextMenuStrip my_menu = new ContextMenuStrip();
int position_xy_mouse_row = dataGridView1.HitTest(e.X, e.Y).RowIndex;
if (position_xy_mouse_row >= 0
{
DataGridViewRow selectedRow = dataGridView1.Rows[position_xy_mouse_row];
dataGridView1.CurrentCell = dataGridView1.Rows[position_xy_mouse_row].Cells[0];
my_menu.Items.Add(new ToolStripMenuItem
{
Name = "Delete",
Text = "Delete",
Tag = "Delete"
});
my_menu.Items.Add(new ToolStripMenuItem
{
Name = "Update",
Text = "Update",
Tag = "Update"
});
my_menu.Show(dataGridView1, new Point(e.X, e.Y));
my_menu.ItemClicked += new ToolStripItemClickedEventHandler(my_menu_ItemClicked);
}
private void my_menu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
var mi = sender as MenuItem;
string menuText = mi.Text;
}
謝謝你這麼多Mark和Sehnsucht!現在更清楚了。 – Gerry