MenuItem Class: Remove all entries except the first (one)

I implemented a new MenuItem Class to fill a Menu from the MenuBar and that is good.

I restrained the “Add one MenuItem” to avoid duplicate and this works (more or less).

I tried to delete all MenuItems by adding a Clear this Menu MenuItem.

And here comes the troubles. I spend the last two hours on the problem:

I can add code in the new Class, but I do not found where / how to get the number of MenuItems (.Count ?)
I can add a MenuHandler in App, but the used code does nothing.

At this stage, beside asking for help, take a dinner and watch TV, I do not know what to do:


Someone, please.


Thanks Tim for the help.

MenuItem.Count leads to an error.
MenuItem.Child / Item / Index works, but without a count…

I have to share the used code / more details. I will do that in a moment.

MenuItem.Count does not lead to an error as long as the MenuItem is not Nil.

MenuItem.Item(index As Integer) is zero-based. So you must do:

For i As Integer = 0 To myMenuItem.Count - 1 ... Next

Thanks Eli.


I used MainMenuBar.Child to get a reference to my Menu, then I was able to get the count of MenuItems and then I was able to remove the items in that menu (leaving my Clear this menu MenuItem).

I do not know what changed since yesterday, but now it seems to work (at last, it removes the menuitems it have to clear) *.

Thank you all for the help (that certainly gaves me the idea to get a reference of my Menu as Child of MainMenuBar and so the access of the MenuItem Count.

I was certainly a victim of Murphy’s cascade error :wink:

  • Now, I have to squash the collateral bugs… in another part of this feature (I seem to save twice some entries into a text file, but this is another story for this afternoon).

Thank you all.

For i As Integer = myMenuItem.Count - 1 downto 1 myMenuItem.Remove(i) Next

That’s it.

Fortunately, I remember that I needed to use To (and Xojo told me about the error, then DownTo…)

The problem was to get MenuItem.Count: that does not worked yesterday (an error was reported) and worked fine after reading the first answers.

It does not matter in this case, but - for the reader - do not use that constuction if your loop can have far more than some tens iterations: myMenuItem.Count - 1 is evaluated at each iteration.


TheCount = myMenuItem.Count - 1

and use TheCount in the for loop.

Since it’s the initial value, it should only be evaluated once. Now, in the construct for i = 1 to MenuItem.Count -1, that would be evaluated each time through the loop.