Skip to main content
A newer version of this page is available. .

How to: Create a custom context menu

  • 2 minutes to read

The following example demonstrates how to create a custom menu, and show it when a node indicator cell is clicked. The menu will contain the “Delete Node” command, allowing an end-user to delete nodes. The result is shown below:

TreeList_CalcHitInfo_CustomMenu_ex

To show the custom menu, the MouseDown event is handled. When this event fires, the TreeList.CalcHitInfo method is called to identify the Tree List element clicked. In the case of clicking a node indicator cell, the custom menu is created and displayed.

An end-user can select the “Delete Node” command within the menu, or close the menu by pressing ESC. If the “Delete Node” command is selected, an event handler (the deleteNodeMenuItemClick method), assigned to the menu item’s Click event, is called. In this event handler, the clicked node is deleted.

To implement the custom menu in this example, the DevExpress.XtraTreeList.Menu.TreeListMenu class is used. This class represents the ancestor for the Tree List standard context menus. You can alternatively use the PopupMenu class, which provides design-time customization capabilities.

using DevExpress.Utils.Menu;
using DevExpress.XtraTreeList;
using DevExpress.XtraTreeList.Nodes;

private void treeList1_PopupMenuShowing(object sender, DevExpress.XtraTreeList.PopupMenuShowingEventArgs e) {
    // Check if a node's indicator cell is clicked.
    TreeListHitInfo hitInfo = (sender as TreeList).CalcHitInfo(e.Point);
    TreeListNode node = null;
    if (hitInfo.HitInfoType == HitInfoType.RowIndicator) {
        node = hitInfo.Node;
    }
    if (node == null) return;
    // Create a menu with a 'Delete Node' item.
    DXMenuItem menuItem = new DXMenuItem("Delete Node", new EventHandler(deleteNodeMenuItemClick));
    menuItem.Tag = node;
    e.Menu.Items.Add(menuItem);
}

private void deleteNodeMenuItemClick(object sender, EventArgs e) {
    DXMenuItem item = sender as DXMenuItem;
    if (item == null) return;
    TreeListNode node = item.Tag as TreeListNode;
    if (node == null) return;
    node.TreeList.DeleteNode(node);

}