C# – Can’t find context menu in control collection

cwinforms

I have a form. This form has a user control. This user control has a panel and a context menu. The context menu is not attached to the panel. There are other controls that are dynamically created and added to this panel. One of those controls is a button. When you click this button, I set the contextmenustrip property to my context menu.

My problem is that I need to read the items in that context menu prior to there being the opportunity to attach the context menu to the button.

Each time a form is loaded, I iterate though all the child controls of the form. If a control has children, I iterate through those, and so on… I can't seem to get at the context menu that is unassigned so to speak. It has not been attached to any control so it does not appear to be a child control of any controls on the form.

myConectMenu is never added to the user conrol like this.Controls.Add(myConectMenu). How can that context menu not be nested in the forms control collection? How can I get at that context menu?

Here is the designer code:

private System.Windows.Forms.ContextMenuStrip myContextMenu;

void InitializeComponent()
{
    this.myContextMenu = new System.Windows.Forms.ContextMenuStrip(this.components);
    this.myContextMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
    this.myToolStripMenuItem1,
    this.myToolStripMenuItem2});
    this.myContextMenu.Name = "myContextMenu";
    this.myContextMenu.Size = new System.Drawing.Size(158, 92);
}

Update
The control iteration happens in a base class from which all forms in my application derive.

There is a private components object that the myContextMenu is added to. I imagine this is there so you can see the context menu in design view when it's not attached to a control. Perhaps I could leverage this?

private System.ComponentModel.IContainer components = null;

this.myContextMenu = new System.Windows.Forms.ContextMenuStrip(this.components);

Best Answer

As you correctly observed, myContextMenu is not added to the Controls connection. Control has ContextMenuStrip property which you should check.

public void FindContextMenuStrip(Control input)
{
    foreach(Control control in input.Controls)
    {
        if(control.ContextMenuStrip != null)
            DoSomethingWithContextMenuStrip(control.ContextMenuStrip)

        if(control.Controls.Count > 0)
            FindContextMenuStrip(control);
    }
}

Put relevant code in DoSomethingWithContextMenuStrip method.

EDIT:

I saw your comment where you specified what you wanted to do with ContextMenuStrip.

How about creating a method in Base class which takes user details and creates a context menu strip?

public ContextMenuStrip GetContextMenuStripForUser(User user)
{
   //code to create context menu strip, with only those items enabled for which user has access.
}

In your final form, use this method to get ContextMenuStrip.

Related Topic