如何以编程方式扩展Treeview?

时间:2013-09-04 17:16:06

标签: c# treeview expand

我编写了以下代码来迭代我的Treeview并找到给定的完整路径。

我得到了正确的位置,listview也显示了正确的内容,treeview未展开。似乎.Expand()方法确实如此不开火。

那可能是什么?

带有Treeview的表单是一个Dialog,在程序启动时初始化一次,然后刷新并在需要时显示。

由于深入的文件夹数量庞大,我只需向下加载2个级别的文件夹,每个文件夹都会手动展开。

在我再次显示对话框之前,我将SelectedPath设置为应该展开的完整路径,而不是调用ExpandToPath方法。

    private void treeView1_BeforeExpand(object sender, System.Windows.Forms.TreeViewCancelEventArgs e) {
        if(e.Node.Tag != null && e.Node.Nodes.Count > 0)
            PopulateTreeView(e.Node, 1);
    }



    private void PopulateTreeView(TreeNode node, int depth) {

        if(node.Tag != null) {

            TreeViewTag tag = node.Tag as TreeViewTag;
            if(tag.Visited && node.Nodes.Count > 0) {

                foreach(TreeNode n in node.Nodes) {
                    if(depth <= 1)
                        PopulateTreeView(n, depth + 1);
                }

            } else {

                TreeNode aNode;
                try {
                    DirectoryInfo[] infos = tag.Info.GetDirectories();

                    foreach(DirectoryInfo subDir in infos) {
                        try {
                            aNode = new TreeNode(subDir.Name, 0, 0);
                            aNode.Tag = new TreeViewTag() { Info = subDir, Visited = true };
                            aNode.ImageKey = "folderOpen";

                            if(depth <= 1)
                                PopulateTreeView(aNode, depth + 1);

                            node.Nodes.Add(aNode);
                        } catch(UnauthorizedAccessException ex11) {
                        } catch(Exception ex12) {
                        }

                    }
                } catch(UnauthorizedAccessException ex1) {
                } catch(Exception ex2) {
                }
            }
        }
    }


    public void ExpandToPath(string path) {
        currentNodeInfo = new DirectoryInfo(path);

        TreeNode root = this.treeView1.Nodes[0];
        if(path.EndsWith(Path.DirectorySeparatorChar.ToString()))
            path = path.Substring(0, path.Length - 1);

        Stack<TreeNode> search = new Stack<TreeNode>();
        search.Push(root);

        while(search.Count > 0) {
            TreeNode current = search.Pop();
            string compare = (current.Tag as TreeViewTag).Info.FullName;
            if(path.Equals(compare)) {
                current.Expand();
                PopulateListView((current.Tag as TreeViewTag).Info);
                break;
            } else {
                if(path.StartsWith(compare)) {
                    current.Expand();
                    foreach(TreeNode node in current.Nodes) {
                        search.Push(node);
                    }
                }
            }
        }
        search.Clear();
        search = null;
    }

0 个答案:

没有答案