Udostępnij za pośrednictwem


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();
    

See Also

Tasks

How to: Set Icons for the Windows Forms TreeView Control

How to: Iterate Through All Nodes of a Windows Forms TreeView Control

How to: Determine Which TreeView Node Was Clicked (Windows Forms)

How to: Add Custom Information to a TreeView or ListView Control (Windows Forms)

Reference

TreeView Control Overview (Windows Forms)

Other Resources

TreeView Control (Windows Forms)