Saving Trees
I also had to consider the hierarchical structure of the group tree when saving its contents to a file. Serialization required the same recursive approach I had used with dragging and dropping tree groups. I wrote the SaveTree method (see treeview.cpp) to handle the task of saving tree data to a file. SaveTree calls the RecurseItem method to save the tree's data recursively. The second parameter to RecurseItem specifies the handler routine that is called to deal with each tree item encountered. I specified the ArchiveItem method for this parameter, because I wanted to save tree data to a file.

ArchiveItem writes the name of each group to the file along with the level number of the group. The level number stores the nesting level of a particular group and is used mainly to restore the tree's structure when tree data is reloaded from a file. For example, if the group News and Weather is immediately below the root of the tree, the group has a level of zero. If this group contains a child group called News, then its level would be one.

The LoadTree method (see treeview.cpp) interprets the level numbers and reconstructs the group tree. As LoadTree adds entries, it keeps an index of the current level number to which it is adding the entries. The index initially starts at zero, which represents the root level of the tree. LoadTree then reads a group's information from the data file and compares the group's level to the current level. If the group's level number is equal to the current level number, it automatically adds a new tree node and assigns the same parent to the node as the parent of the last item added. If the group's level is greater than the current level, the new node is added and its parent is equal to the last item added to the tree. If the group's level number is less than the current level, LoadTree adds the node and assigns the proper parent based on the difference in the levels. For example, if the new group's level is two and the current level is four, the new node's parent is the same as the grandparent of the last item added.