Search code examples
c#.netwinformscontextmenustrip

C# - Duplicate ContextMenuStrip Items into another


I have two ContextMenuStrip(s) in a Windows Form Application, one of them has 3 items and the other one has none.

Let's suppose this:

ContextMenuStrip c1 = new ContextMenuStrip();
ContextMenuStrip c2;

c1 has 3 ToolStripMenuItems, c2 is the ContextMenuStrip destination where c1 items should be duplicated.

I tried to write this:

c2 = new ContextMenuStrip(c1.Container);

but it gives me an ArgumentNullException because c1.Container is Equal to null.

I cant figure out how to solve this, can you help me?

Ps. I would new ToolStripMenuItem(s), no references

and

while or foreach loops solutions are not the best way to do this.

Thank you :)


Solution

  • Then, have a function that creates the ContextMenuStrip and call it each time a new menu is needed

    Func<ContextMenuStrip> newContextMenuStrip = () => { 
        var c = new ContextMenuStrip();
        c.Items.Add("item 1");
        c.Items.Add("item 2");
        c.Items.Add("item 3");
        return c;
    };
    
    var c1 = newContextMenuStrip();
    var c2 = newContextMenuStrip();