WebPart.CreateWebPartMenu method

Called after the Microsoft ASP.NET Load event and used to modify or override the default menu.

Namespace:  Microsoft.SharePoint.WebPartPages
Assembly:  Microsoft.SharePoint (in Microsoft.SharePoint.dll)

public virtual void CreateWebPartMenu()

The CreateWebPartMenu method is called after the inherited System.Web.UI.Control.Load event has occurred to notify the Web Part to set the WebPartMenu property.

The following code example shows an overridden CreateWebPartMenu method that adds a parent menu item and two menu items to the default Web Part menu. It assumes that this method is part of a WebPart class that includes two custom Boolean properties, ParentItemIsVisible and EnableItem1, which allow you to control when these menu items are visible and enabled. An event handler named EventHandlerForItem1 should also be created.

public override void CreateWebPartMenu()
    // Declare variables for menu items.
    MenuItem ParentItem;
    MenuItem Item1;
    MenuItem Item2;

    // Create three menu items:
    // One parent item, and two submenu items.

    // Create the parent item.
    ParentItem = new MenuItem("ParentItem", "", "ParentItemID");

    // Create a submenu item with a server event on click.
    Item1 = new MenuItem("Item1", "Item1ID", new EventHandler(EventHandlerForItem1));

    // Create a submenu item with a client event on click. 
    Item2 = new MenuItem("Item2", "javascript:alert('Item2 was clicked.');", "Item2ID");

    // Add the submenu items to the parent item.

    // Add the parent item after the "Modify Shared/Personal Web Part"
    // command in the default menu. 

    // Retrieve the index of the "Modify Shared/Personal Web Part" command.
    int EditIndex = this.WebPartMenu.MenuItems.IndexOf(this.WebPartMenu.MenuItems.ItemFromID("MSOMenu_Edit"));

    // Insert the parent item after the "Modify Shared/Personal Web Part" command.
    this.WebPartMenu.MenuItems.Insert(EditIndex + 1, ParentItem); 

    // Add a separator above the parent item.
    ParentItem.BeginSection = true;

    // Check the "ParentItemIsVisible" custom Boolean property to decide whether to display the parent menu.
    if (this.ParentItemIsVisible == true)
        ParentItem.Visible = true;

        ParentItem.Visible = false;

    // Check the "EnableItem1" custom Boolean property to decide which menu item to enable. 
    // within the parent item.
    if (this.EnableItem1 == true)