Compartilhar via


How to: Add and Remove Menu Items with the Windows Forms ContextMenu Component

Explains how to add and remove shortcut menu items in Windows Forms.

The Windows Forms ContextMenu component provides a menu of frequently used commands that are relevant to the selected object. You can add items to the shortcut menu by adding MenuItem objects to the MenuItems collection.

You can remove items from a shortcut menu permanently; however, at run time it may be more appropriate to hide or disable the items instead.

NoteImportant

Although MenuStrip and ContextMenuStrip replace and add functionality to the MainMenu and ContextMenu controls of previous versions, MainMenu and ContextMenu are retained for both backward compatibility and future use if you choose.

To remove items from a shortcut menu

  1. Use the Remove or RemoveAt method of the MenuItems collection of the ContextMenu component to remove a particular menu item.

    ' Removes the first item in the shortcut menu.
    ContextMenu1.MenuItems.RemoveAt(0)
    ' Removes a particular object from the shortcut menu.
    ContextMenu1.MenuItems.Remove(mnuItemNew)
    
    // Removes the first item in the shortcut menu.
    contextMenu1.MenuItems.RemoveAt(0);
    // Removes a particular object from the shortcut menu.
    contextMenu1.MenuItems.Remove(mnuItemNew);
    
    // Removes the first item in the shortcut menu.
    contextMenu1.get_MenuItems().RemoveAt(0);
    // Removes a particular object from the shortcut menu.
    contextMenu1.get_MenuItems().Remove(mnuItemNew);
    
    // Removes the first item in the shortcut menu.
    contextMenu1->MenuItems->RemoveAt(0);
    // Removes a particular object from the shortcut menu.
    contextMenu1->MenuItems->Remove(mnuItemNew);
    

    -or-

  2. Use the Clear method of the MenuItems collection of the ContextMenu component to remove all items from the menu.

    ContextMenu1.MenuItems.Clear()
    
    contextMenu1.MenuItems.Clear();
    
    contextMenu1.get_MenuItems().Clear();
    
    contextMenu1->MenuItems->Clear();
    

See Also

Reference

ContextMenu Component Overview (Windows Forms)
ContextMenu

Other Resources

ContextMenu Component (Windows Forms)