Reputation: 16839
How can I determine the parent of a ToolStripMenuItem? With a normal MenuStrip all you have to do is use the Parent property, but it doesn't seem that ToolStripMenuItem has that property. I have a ToolStripDropDownButton that has a couple of ToolStripMenuItems and I'd like to be able to pinpoint the parent of those programatically.
Upvotes: 16
Views: 21906
Reputation: 1
After searching many post to this question, I found that this worked for me:
ToolStripMenuItem mi = (ToolStripMenuItem)sender;
ToolStripMenuItem miOwnerItem = (ToolStripMenuItem)(mi.GetCurrentParent() as ToolStripDropDown).OwnerItem;
Upvotes: 0
Reputation: 1967
Here is what you looking for
private void ContextMenuStrip_Opening(object sender, CancelEventArgs e)
{
contextMenuStrip1.Tag = ((ContextMenuStrip)sender).OwnerItem;
}
private void ToolStripMenuItem_Click(object sender, EventArgs e)
{
ToolStripMenuItem senderItem = (ToolStripMenuItem)sender;
var ownerItem = (ToolStripMenuItem)((ContextMenuStrip)senderItem.Owner).Tag;
}
Upvotes: 0
Reputation: 400
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;
}
}
Upvotes: 6
Reputation: 9393
Try this.....
ToolStripMenuItem t = (ToolStripMenuItem)sender;
ContextMenuStrip s = (ContextMenuStrip)t.Owner;
MessageBox.Show(s.SourceControl.Name);
Upvotes: 4