C# 递归填充 TreeView 堆栈内存溢出
呜呼!我要在 stackoverflow 上发布一个关于堆栈溢出的问题...:)
所以可能只是因为今天是星期五,我的大脑已经崩溃了,但我正在尝试编写一个类,用通用类型递归地填充给定的 TreeView继承自 TreeNode 的对象和一个简单的接口。
由于某种原因,当我尝试填充节点时,出现了 stackoverflow 异常。
我的简单界面:
public interface ITreeNode
{
int ItemID { get; set; }
int ParentID { get; set; }
}
递归代码:
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);
}
}
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

好吧,亨克明白了,这是一个循环。
我有 2 个单独的表,其中包含填充树视图的文件夹项目和报表项目 - 我在两个表中使用标识列作为 ID - 并且该标识对于同时具有另一个文件夹和报表项目作为子项的文件夹是重复的。
我刚刚添加了一个检查以仅调用文件夹项目的递归,现在它工作正常。
我知道这是星期五犯的一个愚蠢的错误。
感谢您的帮助!
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!