2

Woohoo! I get to post a question about a stack overflow...on stackoverflow :)

So it might just be that it's Friday and my brain is already fried, but I am trying to write a class that recursively populates a given TreeView with a generic type of object that inherits from a TreeNode and a simple interface.

For some reason I am getting a stackoverflow exception when I try to populate the nodes.

My simple interface:

public interface ITreeNode
{
    int ItemID { get; set; }
    int ParentID { get; set; }
}

Recursion code:

public void SetNodes(int rootId)
{
    foreach (T root in _nodeList.Where(i => i.ParentID == rootId))
    {
        _tree.Nodes.Add(root);
        addBrowserItems(root);
    }
}

private void addBrowserItems(T parentNode)
{
    foreach (T child in _nodeList.Where(i => i.ParentID == parentNode.ItemID))
    {
        parentNode.Nodes.Add(child);
        addBrowserItems(child);
    }
}
7
  • 1
    @Aliostad - reminded me of a song that comment. Commented Nov 11, 2011 at 16:26
  • Code looks good to me. Have you stepped in to make sure your data is ok? Commented Nov 11, 2011 at 16:28
  • 6
    When your _nodeList contains cycles your stack will overflow. Commented Nov 11, 2011 at 16:30
  • @Adam If I Lazy-Load the data, it works just fine Commented Nov 11, 2011 at 16:32
  • 2
    Ohhhh - @Henk nailed it. Your tree has a cycle. A circular reference. Node X has a parent, that has a parent, whose parent is X. Or some similar mind-bending edge case that's creeped into your data. Commented Nov 11, 2011 at 17:05

1 Answer 1

2

OK, so Henk got it, there was a cycle.

I had 2 seperate tables with folder items and report items that were populating the treeview - I was using an identity column as the ID in both - and the identity was duplicated for a folder that had both another folder and report items as children.

I just added a check to only call the recursion for Folder items and it works perfectly now.

I knew it was a silly Friday mistake.

Thanks for the help!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.