tags:

views:

32

answers:

2

How can I get ContextMenu that a ToolStripDropDownItem belongs to? This is for the purpose of using the ContextMenu.SourceControl as the logical sender to an event.

+1  A: 
`ToolStripItem.OwnerItem` [http://msdn.microsoft.com/en-us/library/system.windows.forms.toolstripitem.owneritem.aspx][1]

That property can be used to walk up the tree of menu items to the top level item... Isn't what you are after just the Owner property of the menu?

var control = ((ContextMenuStrip)topLevelMenuItem.Owner).SourceControl;

Obviously use as etc and do your null checks...

If I am missing the spot perhaps post a code snippet of the menu built via code to clarify the types (ContextMenu vs ContextMenuStrip etc)

PK :-)

Paul Kohler
Did you even try it? Casting `OwnerItem` to `ContextMenu` with an `as` statement doesn't even compile (ie: a `ContextMenu` cannot *be* a `ToolStripItem`).
C. Ross
That's the parent of the menu item.
Paul Kohler
See updated answer...
Paul Kohler
A: 

I needed to use the Owner property as a ContextMenuStrip.

ToolStripDropDownItem t = sender as ToolStripDropDownItem;
if (t == null)
    return null;
ContextMenuStrip cm = t.Owner as ContextMenuStrip;
if (cm == null)
    return null;
return cm.SourceControl;
C. Ross