C# 递归填充 TreeView 堆栈内存溢出

发布于 12-15 13:41 字数 752 浏览 3 评论 0原文

呜呼!我要在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

锦爱2024-12-22 13:41:40

好吧,亨克明白了,这是一个循环。

我有 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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文