Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find parent control of ToolStripMenuItem

I have a ContextMenuStrip that I attach to several controls. It has the items { Add, Remove, Edit }. When a user right clicks on one of my listbox controls (which pops up this context menu) and selects 'Add', how can I derive the listbox control from the ToolStripMenuItem reference that is passed in?

    private void OnAddEntry(object sender, EventArgs e)
    {
        // Example: ?????
        ListBox lb = sender.Parent;
    }
like image 222
MarkP Avatar asked Apr 21 '12 23:04

MarkP


2 Answers

Mark, try this:

((ContextMenuStrip)(((ToolStripMenuItem)sender).Owner)).SourceControl
like image 54
Grant Winney Avatar answered Sep 28 '22 18:09

Grant Winney


I'm guessing you can go up the chain of parents until you find the listbox.

You may be able to speed this up using the OwnerItem property to get straight to the toolstrip.

You could always set the item's Tag to the listbox and then just use it as require.

like image 37
John3136 Avatar answered Sep 28 '22 17:09

John3136