The following code shows how the program loads the TreeView control.
// Load a TreeView control from a file that uses tabs
// to show indentation.
private void LoadTreeViewFromFile(string file_name, TreeView trv)
{
// Get the file's contents.
string file_contents = File.ReadAllText(file_name);
// Break the file into lines.
string[] lines = file_contents.Split(
new char[] {'\r', '\n'},
StringSplitOptions.RemoveEmptyEntries);
// Process the lines.
trv.Nodes.Clear();
TreeNode[] tree_nodes = new TreeNode[0];
foreach (string text_line in lines)
{
// See how many tabs are at the start of the line.
int level = text_line.Length -
text_line.TrimStart('\t').Length;
// Make sure there's room for the node at this level.
if (level >= tree_nodes.Length)
{
// Make room.
Array.Resize(ref tree_nodes, tree_nodes.Length + 1);
}
// Add the new node.
if (level == 0)
{
tree_nodes[level] = trv.Nodes.Add(text_line.Trim());
}
else
{
tree_nodes[level] = tree_nodes[level - 1].Nodes.Add(text_line.Trim());
}
tree_nodes[level].EnsureVisible();
}
if (trv.Nodes.Count > 0) trv.Nodes[0].EnsureVisible();
}
First the program uses System.IO.File.ReadAllText to read the text file into a string. It then splits the file into lines using \r and \n characters as delimiters. It removes any blank lines, which may represent actual blank lines or may be due to the file containing \r\n combinations.
Next the code clears the TreeView control and creates the tree_nodes array to hold the most recent node at each level of the tree. For example, tree_nodes[2] will be a reference to the most recent node at level 2 of the tree. Then if the program needs to add a node at level 3 of the tree, it can use tree_nodes[2] as its parent.
Initially the tree_nodes array exists but has 0 entries in it.
Next the code loops over the lines in the file. For each line, it determines how many tab characters are at the beginning of the line. That gives the node's level in the tree.
If the node's level is greater than the number of entries in the tree_nodes array, then this is a new depth for the tree. The code resizes the tree_nodes array to make room to store the node at this new depth.
Now the code creates the new node. If the node is at level 0, the code adds it to the TreeView's Nodes collection to make it a top-level node. If the node is not at level 0, the code adds it as a child to the previously saved node at level - 1 in the tree, which was recorded in tree_nodes[level - 1]. In either case, the code saves the new node in tree_nodes[level] in case the program needs to add a node as a child of this one.
After adding the node, the program calls the node's EnsureVisible method to make sure its parent is expanded.
After adding all nodes, the code ensures the first node is visible so the TreeView displays its top node if it is too long to show all of the nodes at the same time.
Comments