Fill a TreeView with a Just-In-Time Directory Tree

Problem

You need to show a directory tree with the TreeView control, but filling the directory tree structure at startup is too time consuming.

Solution

React to the BeforeExpand event to fill in subdirectories just before they are displayed.

Discussion

You can use the recursion technique shown in recipe Process Files Recursively to build an entire directory tree. However, scanning the file system in this way can be slow, particularly for large drives. For this reason, professional file management software (and Windows Explorer) use a different technique—they query the necessary directory information when the user requests it.

The TreeView control, shown in Figure 5-1, is particularly well suited to ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.