Export (0) Print
Expand All

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.
    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();
    
Show:
© 2014 Microsoft