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
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.

How to: Add and Remove Nodes with the Windows Forms TreeView Control

The Windows Forms TreeView control stores the top-level nodes in its Nodes collection. Each TreeNode also has its own Nodes collection to store its child nodes. Both collection properties are of type TreeNodeCollection, which provides standard collection members that enable you to add, remove, and rearrange the nodes at a single level of the node hierarchy.

To add nodes programmatically

  • Use the Add method of the tree view's Nodes property.

    ' Adds new node as a child node of the currently selected node.
    Dim newNode As TreeNode = New TreeNode("Text for new node")
    TreeView1.SelectedNode.Nodes.Add(newNode)
    

    // Adds new node as a child node of the currently selected node.
    TreeNode newNode = new TreeNode("Text for new node");
    treeView1.SelectedNode.Nodes.Add(newNode);
    

    // Adds new node as a child node of the currently selected node.
    TreeNode newNode = new TreeNode("Text for new node");
    treeView1.get_SelectedNode().get_Nodes().Add(newNode);
    

    // Adds new node as a child node of the currently selected node.
    TreeNode ^ newNode = new TreeNode("Text for new node");
    treeView1->SelectedNode->Nodes->Add(newNode);
    

To remove nodes programmatically

  • Use the Remove method of the tree view's Nodes property to remove a single node, or the Clear method to clear all nodes.

    ' Removes currently selected node, or root if nothing is selected.
    TreeView1.Nodes.Remove(TreeView1.SelectedNode)
    ' Clears all nodes.
    TreeView1.Nodes.Clear()
    

    // Removes currently selected node, or root if nothing 
    // is selected.
    treeView1.Nodes.Remove(treeView1.SelectedNode);
    // Clears all nodes.
    TreeView1.Nodes.Clear();
    

    // Removes currently selected node, or root if nothing 
    // is selected.
    treeView1.get_Nodes().Remove(treeView1.get_SelectedNode());
    

    // Removes currently selected node, or root if nothing
    // is selected.
    treeView1->Nodes->Remove(treeView1->SelectedNode);
    // Clears all nodes.
    treeView1->Nodes->Clear();
    

Community Additions

ADD
Show:
© 2015 Microsoft