迭代通过List在TreeView中显示

时间:2018-06-06 03:43:12

标签: c# .net winforms treeview

我有四个列表,我试图将内容显示在TreeView的{​​{1}}上。
我目前的问题是只有每个列表中的最后一项显示在视图中 我确信它与我如何迭代列表有关,但我很困惑如何让每个单独的列表项显示在树中。

我的树形结构是:

Form

我在树视图所在的Dog Husky huskylist Chiwawa chiwawlist Cat Siamese siameselist Tabby tabbylist 的代码:

Form

1 个答案:

答案 0 :(得分:2)

  

在c#Refer here

中创建对象和动态数组      

TreeView Basic了解Refer here

在创建子节点时,您将覆盖该实例。你应该维护一个数组中的节点。

        //tree code

        //add husky list
        List<TreeNode> node8 = new List<TreeNode>();
        foreach (var item in huskyList)
        {
            node8.Add(new TreeNode(item.name));
        }

        TreeNode[] husky = node8.ToArray();

        //add chiwawa list
        List<TreeNode> node9 = new List<TreeNode>();
        foreach (var item in chiwawaList)
        {
            node9.Add(new TreeNode(item.name));
        }

        TreeNode[] chiwawa = node9.ToArray();

        //dog breed
        TreeNode node2 = new TreeNode("Husky", husky);
        TreeNode node3 = new TreeNode("Chiwawa", chiwawa);
        TreeNode[] dog = new TreeNode[] { node2, node3 };

        //dog parent
        TreeNode treeNode = new TreeNode("Dogs", dog);
        treeView1.Nodes.Add(treeNode);

        //add tabby list
        List<TreeNode> nodes = new List<TreeNode>();

        foreach (var item in tabbyList)
        {
            nodes.Add(new TreeNode(item.name));
        }

        TreeNode[] tabby =nodes.ToArray();

        //add siamese list
        List<TreeNode> node7 = new List<TreeNode>();
        foreach (var item in siameseList)
        {
            node7.Add(new TreeNode(item.name));
        }

        TreeNode[] siamese = node7.ToArray();

        //cat breed
        TreeNode node4 = new TreeNode("Siamese", siamese);
        TreeNode node5 = new TreeNode("Tabby", tabby);
        TreeNode[] cat = new TreeNode[] { node4, node5 };

        //cat parent
        treeNode = new TreeNode("Cats", cat);
        treeView1.Nodes.Add(treeNode);

或者 使用LINQ,您可以像这样创建树

        // Code Using Linq
        TreeNode husky = new TreeNode("Husky", huskyList.Select(x => new TreeNode(x.name)).ToArray());
        TreeNode chiwawa = new TreeNode("Chiwawa", chiwawaList.Select(x => new TreeNode(x.name)).ToArray());
        TreeNode Siamese = new TreeNode("Siamese", siameseList.Select(x => new TreeNode(x.name)).ToArray());
        TreeNode Tabby = new TreeNode("Tabby", tabbyList.Select(x => new TreeNode(x.name)).ToArray());
        //parent nodes
        treeView1.Nodes.AddRange(new[] {
            new TreeNode("Dog", new TreeNode[] { husky, chiwawa }),
            new TreeNode("Cat", new TreeNode[] { Siamese, Tabby })
            });