Question

I want to transfer items of contextmenustrip to other using items.addrange method. I can transfer items one by one using a for loop:

For each Item in ContextMenuStrip1.items
ContextMenuStrip2.Items.Add(item)
Next

But how I can transfer items using items.addrange method?

Was it helpful?

Solution

You need to copy the elements from the original ContextMenuStrip in an array (CopyTo seems enough for this), Then it is simple to add the array to the second ContextMenuStrip

Dim tsi(ContextMenuStrip1.Items.Count - 1) As ToolStripItem
ContextMenuStrip1.Items.CopyTo(tsi, 0)
ContextMenuStrip2.Items.AddRange(tsi)

OTHER TIPS

The loop you have now has the exact same problem that using AddRange() has. It is modifying the Items collection as the item is moved from one CMS to another. That bombs your code when the index becomes invalid.

One safe way to do this is by iterating the Items list backwards so the changes to the collection doesn't make the index invalid. Like this:

    For ix = ContextMenuStrip1.Items.Count - 1 To 0 Step -1
        ContextMenuStrip2.Items.Insert(0, ContextMenuStrip1.Items(ix))
    Next

If you want to use AddRange then you need to make a copy of the Items collection so that moving the items doesn't invalidate the source. You can use Linq for that, like this, spelled out for clarity:

    Dim items = ContextMenuStrip1.Items.OfType(Of ToolStripItem).ToArray()
    ContextMenuStrip2.Items.AddRange(items)

To copy your contextmenu1 to contextmenu2 ..

Private Sub CopyMyMenus()
    ' Create empty array to store ContextMenuStrip1 objects.
    Dim myItems(ContextMenuStrip1.MenuItems.Count) As MenuItem

    ' Copy elements of the ContextMenuStrip1 MenuItem collection to array.
    ContextMenuStrip1.MenuItems.CopyTo(myItems, 0)

    ' Add the array to the menu item collection of the ContextMenu.
    contextMenu2.MenuItems.AddRange(myItems)

End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top