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

Adding and Removing Nodes with the Windows Forms TreeView Control

Visual Studio .NET 2003

Because the Windows Forms TreeView control displays nodes in a hierarchical manner, when adding a node you must pay attention to what its parent node is.

To add or remove nodes in the designer

  1. Select the TreeView control or add one to the form.
  2. In the Properties window, click the ellipsis (Aa984278.vbellipsesbutton(en-us,VS.71).gif) button next to the Nodes property.

    The TreeNode Editor appears.

  3. To add nodes, a root node must exist; if one does not exist, you must first add a root by clicking the Add Root button. You can then add child nodes by selecting the root or any other node and clicking the Add Child button. To delete nodes, select the node to delete and then click the Delete button.

To add nodes programmatically

  • Use the Add method of the tree view's Nodes property.
    ' Visual Basic
    ' 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)
    
    // C#
    // 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);
    
    // C++
    // Adds new node as a child node of the currently selected node.
    TreeNode * newNode = new TreeNode(S"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.
    ' Visual Basic
    ' Removes currently selected node, or root if nothing is selected.
    TreeView1.Nodes.Remove(TreeView1.SelectedNode)
    ' Clears all nodes.
    TreeView1.Nodes.Clear()
    
    // C#
    // Removes currently selected node, or root if nothing 
    // is selected.
    treeView1.Nodes.Remove(treeView1.SelectedNode);
    // Clears all nodes.
    TreeView1.Nodes.Clear();
    
    // C++
    // Removes currently selected node, or root if nothing
    // is selected.
    treeView1->Nodes->Remove(treeView1->SelectedNode);
    // Clears all nodes.
    treeView1->Nodes->Clear();
    

See Also

Introduction to the Windows Forms TreeView Control | Setting Icons for the Windows Forms TreeView Control | Iterating Through All Nodes of a Windows Forms TreeView Control | Determining Which TreeView Node Was Clicked (Windows Forms) | Adding Custom Information to a TreeView or ListView Control (Windows Forms)

Show:
© 2015 Microsoft