I have a ContextMenuStrip
that is assigned to several different listboxes. I am trying to figure out when the ContextMenuStrip
is clicked what ListBox
it was used on. I tried the code below as a start but it is not working. The sender
has the correct value, but when I try to assign it to the menuSubmitted
it is null.
private void MenuViewDetails_Click(object sender, EventArgs e)
{
ContextMenu menuSubmitted = sender as ContextMenu;
if (menuSubmitted != null)
{
Control sourceControl = menuSubmitted.SourceControl;
}
}
Any help would be great. Thanks.
Using the assistance below, I figured it out:
private void MenuViewDetails_Click(object sender, EventArgs e)
{
ToolStripMenuItem menuItem = sender as ToolStripMenuItem;
if (menuItem != null)
{
ContextMenuStrip calendarMenu = menuItem.Owner as ContextMenuStrip;
if (calendarMenu != null)
{
Control controlSelected = calendarMenu.SourceControl;
}
}
}
For a
ContextMenu
:The problem is that the
sender
parameter points to the item on the context menu that was clicked, not the context menu itself.It's a simple fix, though, because each
MenuItem
exposes aGetContextMenu
method that will tell you whichContextMenu
contains that menu item.Change your code to the following:
For a
ContextMenuStrip
:It does change things slightly if you use a
ContextMenuStrip
instead of aContextMenu
. The two controls are not related to one another, and an instance of one cannot be casted to an instance of the other.As before, the item that was clicked is still returned in the
sender
parameter, so you will have to determine theContextMenuStrip
that owns this individual menu item. You do that with theOwner
property. Finally, you'll use theSourceControl
property to determine which control is displaying the context menu.Modify your code like so: