C# - Get Parent of ToolStripMenuItem

Try the OwnerItem property.


This works for me:

ToolStripMenuItem menuItem = sender as ToolStripMenuItem;

ToolStrip toolStrip = menuItem.GetCurrentParent();

...from this, you can devise a method to bring you from a random ToolStripMenuItem to the top-most level such:

public static class ToolStripItemExtension
{
    public static ContextMenuStrip GetContextMenuStrip(this ToolStripItem item)
    {
        ToolStripItem itemCheck = item;            

        while (!(itemCheck.GetCurrentParent() is ContextMenuStrip) && itemCheck.GetCurrentParent() is ToolStripDropDown)
        {
            itemCheck = (itemCheck.GetCurrentParent() as ToolStripDropDown).OwnerItem;
        }

        return itemCheck.GetCurrentParent() as ContextMenuStrip;
    }
}

Try this.....

ToolStripMenuItem t = (ToolStripMenuItem)sender;
ContextMenuStrip s = (ContextMenuStrip)t.Owner;
MessageBox.Show(s.SourceControl.Name);

Tags:

C#

Winforms