Menu.MenuItemCollection.Add Method (String, EventHandler)

 
System_CAPS_noteNote

The .NET API Reference documentation has a new home. Visit the .NET API Browser on docs.microsoft.com to see the new experience.

Adds a new MenuItem to the end of the current menu with a specified caption and a specified event handler for the Click event.

Namespace:   System.Windows.Forms
Assembly:  System.Windows.Forms (in System.Windows.Forms.dll)

public virtual MenuItem Add(
	string caption,
	EventHandler onClick
)

Parameters

caption
Type: System.String

The caption of the menu item.

onClick
Type: System.EventHandler

An EventHandler that represents the event handler that is called when the item is clicked by the user, or when a user presses an accelerator or shortcut key for the menu item.

Return Value

Type: System.Windows.Forms.MenuItem

A MenuItem that represents the menu item being added to the collection.

A MenuItem can only be contained in one menu at a time, and cannot be added more than once to the same menu. To reuse a MenuItem in more than one menu, use the CloneMenu method of the MenuItem class. To remove a MenuItem that you have previously added, use the Remove method.

This version of the Add method allows you to specify a caption for the menu item and a delegate to handle the Click event. You can use this version of the Add method if your application already has an event handler to handle the Click event.

System_CAPS_noteNote

The Click event is not raised for a MenuItem that contains submenu items.

The following code example uses the derived class MainMenu to create a main menu, mainMenu1, that has two MenuItem objects added to its MenuItems collection. The code uses this version of the Add method to define an event handler for the Click event of the second menu item added to the collection. The code then assigns mainMenu1 to the Menu property of the Form. This example requires that the code defined in this example is located within a form.

private void InitializeMyMainMenu()
{
   // Create the MainMenu.
   MainMenu mainMenu1 = new MainMenu();

   /* Use the MenuItems property to call the Add method
      to add two new MenuItem objects to the MainMenu. */
   mainMenu1.MenuItems.Add ("&File");
   mainMenu1.MenuItems.Add ("&Edit", new EventHandler (menuItem2_Click));

   // Assign mainMenu1 to the form.
   this.Menu = mainMenu1;
}

private void menuItem2_Click(System.Object sender, System.EventArgs e)
{
   // Insert code to handle Click event.
}

.NET Framework
Available since 1.1
Return to top
Show: