FyreeW
FyreeW

Reputation: 415

Stack overflow when creating TreeView

I am getting a stack overflow, when I try to create a Tree View using WinForms.

private void createFeatureTree()
{
    FeatureTree.Nodes.Clear();
    FeatureTree.Nodes.Add(createTreeNode(new DirectoryInfo(starting directory path)));
}

private TreeNode createTreeNode(DirectoryInfo directory)
{
   var directoryNode = new TreeNode(directory.Name);
   foreach (var dir in directory.GetDirectories())
   {
       directoryNode.Nodes.Add(createTreeNode(directory));
   }

   foreach (var file in directory.GetFiles())
   {
       directoryNode.Nodes.Add(new TreeNode(file.Name));
   }

   return directoryNode;
}

createFeatureTree() is called on its own thread on the startup. How come I am getting a stack overflow error? Is there a limit to the amount of nodes that the TreeView can store?

Upvotes: 0

Views: 521

Answers (1)

Jure
Jure

Reputation: 1176

Change a call

directoryNode.Nodes.Add(createTreeNode(directory));

to:

directoryNode.Nodes.Add(createTreeNode(dir));

And it should work. The reason you are getting "StackOverflowException" is that you always call createTreeNode method on directory variable passed in, not on its subdirectories (which, eventually, there would be none when you are at the leaf level).

Basicaly, if you pass in "C:\", you constantly call createTreeNode on "C:\" and it never ends.

Upvotes: 2

Related Questions