Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

How to: Attach a ShortCut Menu to a TreeView Node

The Windows Forms TreeView control displays a hierarchy of nodes, similar to the files and folders displayed in the left pane of Windows Explorer. By setting the ContextMenuStrip property, you can provide context-sensitive operations to the user when they right-click the TreeView control. By associating a ContextMenuStrip component with individual TreeNode items, you can add a customized level of shortcut menu functionality to your TreeView controls.

To associate a shortcut menu with a TreeNode programmatically

  1. Instantiate a TreeView control with the appropriate property settings, create a root TreeNode, and then add subnodes.

  2. Instantiate a ContextMenuStrip component, and then add a ToolStripMenuItem for each operation you want to make available at run time.

  3. Set the ContextMenuStrip property of the appropriate TreeNode to the shortcut menu you create.

  4. When this property is set, the shortcut menu will be displayed when you right-click the node.

The following code example creates a basic TreeView and ContextMenuStrip associated with the root TreeNode of the TreeView. You will need to customize the menu choices to those that fit the TreeView you are developing. Additionally, you will want to write code to handle the Click events for these menu items.

    // Declare the TreeView and ContextMenuStrip 
    private TreeView menuTreeView;
    private ContextMenuStrip docMenu;

    public void InitializeMenuTreeView()
    {
        // Create the TreeView.
        menuTreeView = new TreeView();
        menuTreeView.Size = new Size(200, 200);

        // Create the root node.
        TreeNode docNode = new TreeNode("Documents");

        // Add some additional nodes.
        docNode.Nodes.Add("phoneList.doc");
        docNode.Nodes.Add("resume.doc");

        // Add the root nodes to the TreeView.
        menuTreeView.Nodes.Add(docNode);

        // Create the ContextMenuStrip.
        docMenu = new ContextMenuStrip();

        //Create some menu items.
        ToolStripMenuItem openLabel = new ToolStripMenuItem();
        openLabel.Text = "Open";
        ToolStripMenuItem deleteLabel = new ToolStripMenuItem();
        deleteLabel.Text = "Delete";
        ToolStripMenuItem renameLabel = new ToolStripMenuItem();
        renameLabel.Text = "Rename";

        //Add the menu items to the menu.
        docMenu.Items.AddRange(new ToolStripMenuItem[]{openLabel, 
            deleteLabel, renameLabel});

        // Set the ContextMenuStrip property to the ContextMenuStrip.
        docNode.ContextMenuStrip = docMenu;

        // Add the TreeView to the form. 
        this.Controls.Add(menuTreeView);
    }
Show:
© 2015 Microsoft