TreeView

A TreeView shows a hierarchy: folders and files, a category tree, the sections of a document. Each node is a TreeNode with its own children, so the control is a tree of objects and the code that fills it is a recursion. That recursion is the part with a lesson in it, and it runs on this machine.

A tree of nodes

using System; using System.Drawing; using System.Windows.Forms; internal static class Program { [STAThread] private static void Main() { ApplicationConfiguration.Initialize(); Application.Run(new Form1()); } } internal sealed class Form1 : Form { private readonly TreeView _folders = new() { Dock = DockStyle.Fill, HideSelection = false, ShowLines = true, ShowRootLines = true, HotTracking = true, PathSeparator = "/", }; public Form1() { Text = "Folders"; ClientSize = new Size(360, 300); var notes = new TreeNode("notes") { Tag = "C:/notes" }; notes.Nodes.Add(new TreeNode("2026") { Tag = "C:/notes/2026" }); notes.Nodes.Add(new TreeNode("ideas.txt") { Tag = "C:/notes/ideas.txt" }); var archive = new TreeNode("archive") { Tag = "C:/archive" }; _folders.Nodes.Add(notes); _folders.Nodes.Add(archive); _folders.ExpandAll(); _folders.AfterSelect += (sender, e) => Text = $"selected: {e.Node?.FullPath ?? "none"}"; Controls.Add(_folders); } }

dotnet build app.csproj

Build succeeded.
    0 Warning(s)
    0 Error(s)

The listing is built and not run. A node's Tag carries the path, exactly as a list row carries its id, and FullPath is the text of the node from the root down with PathSeparator between the parts, which is a readable label but not a file path: two nodes with the same name make it ambiguous, which is why the Tag is the value the program reads.

Nodes and children

A tree that is filled in one go is fine for a few hundred nodes. A tree of a real file system is filled lazily: one placeholder child under each folder, replaced by the real children in BeforeExpand, and BeginUpdate() and EndUpdate() around a large fill to stop the control drawing after every add.

Selection and expansion

A folder tree that runs

Filling a tree from a list of paths is a recursion over the parts of each path, and it runs here:

using System; using System.Collections.Generic; using System.Linq; var paths = new[] { "notes/2026/a.txt", "notes/2026/b.txt", "notes/ideas.txt", "archive/old.txt" }; var root = new Node("(root)"); foreach (var path in paths) { root.Add(path.Split('/')); } root.Print(0); Console.WriteLine($"nodes: {root.Count()}"); Console.WriteLine($"find notes/2026: {root.Find("notes/2026")?.Name ?? "missing"}"); Console.WriteLine($"find notes/1999: {root.Find("notes/1999")?.Name ?? "missing"}"); internal sealed class Node { private readonly List<Node> _children = new(); public Node(string name) => Name = name; public string Name { get; } public IReadOnlyList<Node> Children => _children; public void Add(IReadOnlyList<string> parts, int index = 0) { if (index == parts.Count) { return; } var child = _children.FirstOrDefault(node => node.Name == parts[index]); if (child is null) { child = new Node(parts[index]); _children.Add(child); } child.Add(parts, index + 1); } public void Print(int depth) { Console.WriteLine($"{new string(' ', depth * 2)}{Name}"); foreach (var child in _children) { child.Print(depth + 1); } } public Node? Find(string path) { var node = this; foreach (var part in path.Split('/')) { node = node._children.FirstOrDefault(child => child.Name == part); if (node is null) { return null; } } return node; } public int Count() => 1 + _children.Sum(child => child.Count()); }

dotnet run

(root)
  notes
    2026
      a.txt
      b.txt
    ideas.txt
  archive
    old.txt
nodes: 8
find notes/2026: 2026
find notes/1999: missing

The output is the real run. The recursion shares a node when two paths name the same folder, which is why notes appears once with three children rather than twice; the count of eight is the whole tree including the root. Find walks the parts and answers null for a path that is not there, which is the lookup a form makes when it restores the node the user had selected. In a TreeView the same code adds TreeNode objects to Nodes, and the print is the control's job.

Exercises

  1. Add the path notes/2027/c.txt and run the program. What do nodes and the print show?
  2. Make Find return the deepest node that exists for a path that is partly missing, and run it with notes/2026/a.txt/x.
  3. Explain from the documentation what BeginUpdate and EndUpdate do to the drawing of the control.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is a node of a TreeView?

    Answer

    A TreeNode with its own child collection

    The tree is a tree of objects, and filling it is a recursion.

  2. What does FullPath give?

    Answer

    The text of the nodes from the root, joined by PathSeparator

    It is a label, not a file system path, and two equal names make it ambiguous.

  3. Which event fires when a node is selected?

    Answer

    AfterSelect

    BeforeSelect can cancel the change.

  4. How does a form refuse to leave a node?

    Answer

    Set e.Cancel = true in BeforeSelect

    The event carries TreeViewCancelEventArgs for exactly that.

  5. What does ExpandAll do on a large tree?

    Answer

    Expands every branch, which is slow

    The usual answer is to expand only the restored path.

  6. Which calls stop the control drawing during a large fill?

    Answer

    BeginUpdate and EndUpdate

    A tree that redraws after every add of a thousand nodes is unusable.

  7. Why does a handler that sets Checked need the e.Action guard?

    Answer

    Setting Checked raises AfterCheck again

    TreeViewAction.Unknown marks the change made from code.

  8. What did the run print for the node count?

    Answer

    8

    The root, two folders and their children.

  9. Why does notes appear once in the tree?

    Answer

    The recursion reuses a node whose name is already there

    That is what the FirstOrDefault lookup in Add does.

  10. Which event gives the node under the pointer for a context menu?

    Answer

    NodeMouseClick, with e.Node

    SelectedNode may not be the node that was right-clicked yet.

Every listing on this page was built with the .NET SDK 10.0.303 for net10.0-windows against the targeting pack Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed, in a Docker container on Alpine Linux 3.24.3 (x86_64). The programs were built, not run on Linux: WinForms needs Windows. The logic that draws nothing was also run headless on the same machine, and its output is the run output printed below each of those programs.

Article author: Arthur Isaev