问题
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:
- 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 andDropDownItems.Clear()
to remove all the children for an item.
来源:https://stackoverflow.com/questions/4041815/adding-and-removing-toolstripmenuitems-from-menustrip-and-dropdownitems-in-winf