Reputation: 773
I've written a usercontrol that, in essence, is a palette of widgets. When the user right-clicks on one of the widgets that I've drawn on the control, I want to allow the user to delete the selected widget.
In the MouseClick event handler of my usercontrol, I determine which widget the user has clicked on. I then check to see if the mousebutton is the right button. If so, I display a menu that should allow the user to delete the widget:
if (e.Button == MouseButtons.Right)
{
ContextMenu deleteMenu = new ContextMenu();
MenuItem deleteItem = new MenuItem("Delete...", new System.EventHandler(this.onDeleteMenuItem_Click));
deleteMenu.MenuItems.Add("Delete");
deleteMenu.Show(this, new Point(mouseXPosition, mouseYPosition));
}
My handler for this item is:
private void onDeleteMenuItem_Click(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine("Deleting...");
}
When I right-click, the menu is displayed, but the handler never gets called. What am I doing wrong?
Upvotes: 2
Views: 5055
Reputation: 44921
I suspect it is because you are not adding the menu item:
Change this line of code:
deleteMenu.MenuItems.Add("Delete");
to:
deleteMenu.MenuItems.Add(deleteItem);
Upvotes: 6