[Gtk-sharp-list] How to remove menuitems from a menu

Christopher David Howie me at chrishowie.com
Tue Apr 27 10:48:36 EDT 2010

On 04/14/2010 03:27 PM, Davide Lasagna wrote:
> I'm quite new to gtksharp. I have a menu which i want to update in
> response of some event.
> The first 6 items must always remain there, then i have to append some
> menuitems which 
> change at each call to this method.
> Here is the code that i have at the moment.
> The variable gomenu is the menu to be modified.
> void UpdateGoToHistoryMenu()
> {
> // first i need to uderstand how to remove the previously added menuitems
>                         // because otherwise i will continue to add
> elements.
>                         // Here i want to remove the menuitems from 7 to
> end. How do i do this?
> // then i can add elements
> System.Collections.Generic.List<string> hist = history.GetElements();
> for ( int i=0; i < hist.Count - 1; i++ )
> {
> ImageMenuItem item = new ImageMenuItem( hist[i] ){
> Image = new Image(Stock.Directory, IconSize.Menu )};
> gomenu.Insert(item, 6);
> item.Show();
> }
> }
> Basically i want to remove the menuitems from index 6 to the end of the
> menu.

Manipulating menu items by index is never a good idea.  What happens if
you want to add some more permanent items to the menu, or remove some?
Avoid magic numbers wherever possible.

A better solution would be to keep a List<MenuItem> around for your
history items.  In that loop, add "item" to this list.  Clearing the
menu is then as easy as:

for (var i in historyItems)


I would also replace gomenu.Insert() with gomenu.Append(), though this
will probably require reversing your loop direction.  It will, however,
ultimately be a cleaner approach.

Chris Howie

PGP key:

pub   2048R/CF8338F5 2010-04-14
      Fingerprint: 2B7A B280 8B12 21CC 260A  DF65 6FCE 505A CF83 38F5

More information about the Gtk-sharp-list mailing list