Loading tree views the easy way

by Kent Reisdorph

Tree views offer a convenient way of displaying hierarchical information. One of the problems with tree views, however, is that loading the tree view can be tedious. It is tedious because you need to first create a node and then create one or more sub-nodes under that node. Also, you may need to add individual items to specific nodes.

Fortunately, TTreeView has a LoadFromFile() method that makes it very easy to populate a tree view. You can use LoadFromFile() any time you have a tree view that contains static information. (If your tree views display dynamically determined information then you will need to load the tree the hard way.)

As you might expect, the LoadFromFile() method takes the name of a file as a parameter. The file is a text file in a specific format that TTreeView expects. The format is very simple: each level of the tree view is indented one space. Take the following text, for example:

Dogs

Big dogs

Rottweiler

Doberman Pinscher

Great Dane

Small dogs

Jack Russell Terrier

Yorkshire Terrier

Toy Poodle

Cats

Good cats

(none)

Other cats

Mexican Hairless

Siamese

Cheshire

Once you have created the text file, the code to load it into the tree view is simple:

TreeView1->LoadFromFile("c:\\pets.txt");

Figure A shows the tree view as it looks after loading this text using the LoadFromFile() method. As you can see, the topics "Dogs" and "Cats" are top-level nodes in the tree view. Under the "Dogs" node are nodes called "Big dogs" and "Small dogs". Each of these nodes has individual items. The "Cats" node is structured the same way.

Figure A

Populating a TTreeView is easy with the LoadFromStream() method.

In addition to LoadFromFile(), TTreeView has a LoadFromStream() method. This method allows you to populate a tree view from any TStream descendant. Loading a tree view from a stream presents many opportunities, including loading the tree view from a database field or from a resource bound to the EXE.

The LoadFromFile() and LoadFromStream() methods are invaluable any time you need to load a tree view from static text.