Search code examples
c#contextmenustriptoolstripitem

How to reach ToolStripMenu items of the contextMenuStrip?


I am new at C#. I have added a contextMenuStrip in the desing part, and also I added 4 different ToolStriptItem. Three of them are ToolStriptMenuItem, named like successToolStripMenuItem etc. , and one of them is ToolStripTextBox.

What I want is to reach all members of contextMenuStrip. Is there any way to put all items into an array?

I know there is a code like that:

ToolStripItem[] tsi = contextMenuStrip.Items.Find("successToolStripMenuItem", true);

This code is not handy, because only returns 1 member, however I want to get all four elements into the array. That's why I can easily reach them and use them. If my only option is using the code above, I will need to create three more ToolStripItem array, which will have only one member either. This did not seem much practical solution to me.

Thanks in advance


Solution

  • The code you are looking for is here:

    ToolStripItem[] tsi = new ToolStripItem[] { successToolStripMenuItem,
                                                successToolStripTextBox };
    

    The other way to do this, without having to manually add the items, is shown below:

    ToolStripItem[] tsi = new ToolStripItem[contextMenuStrip.Items.Count];
    contextMenuStrip.Items.CopyTo(tsi, 0);
    

    But just so you know, contextMenuStrip.Items is a Collection meaning you can address the items in that collection just like you would for an array. For example:

    contextMenuStrip.Items[0]