views:

24

answers:

1

I have MenuStrip with some static items. To this MenuStrip I am adding items programmatically. Some of these items has child items (DropDownItems).

At some point I would like to remove all added items to recreate menu with different items. How to do it right?

Example situation:

mainMenu
 -staticItem1
 -added1
  -added1_sub1
  -added1_sub2
 -added2
  -added2_sub1

I could do:

added1.Dispose();
mainMenu.Items.Remove(added2);

Both of this works, but I am not sure if it's safe. Maybe I should remove and dispose all items and subitems one by one recursively?

+1  A: 
  • Use Remove method only, it's enough
  • You don't need recursive, When you remove a parent all its children will be removed
  • Use Items.Clear() to remove all the children for the Menu and DropDownItems.Clear() to remove all the children for an item.
Homam
I can't see in Reflector that `Remove` disposes an item. I saw that disposing an item will remove attached events eg. on item click, so the item could be collected by GC. Will item be collected by GC after calling `Remove` on that collection?
prostynick
Yes, In your case, you don't need to call Dispose, the item will be removed from memory when the GC finds it convenient.
Homam
OK, but I am still wondering about `Click` event. I think I should unsubscribe from this event, because GC will not collect it. Am I right?
prostynick
No, you don't need to unsubscribe the events handlers, Because this reference is only one way. So, nothing related to the event handler will stop the GC.
Homam
It seems you're still worried, check read http://social.msdn.microsoft.com/forums/en-US/netfxbcl/thread/3c5552ea-4241-46b4-b1cf-c8b9ee9c639b/ ,Read about Dispose method http://msdn.microsoft.com/en-us/library/system.idisposable.dispose%28v=VS.71%29.aspx http://msdn.microsoft.com/en-us/library/b1yfkh5e%28VS.71%29.aspx
Homam