2

我有这个代码:

    public void AddNode(string Node)
    {
        try
        {
            treeView.Nodes.Add(Node);
            treeView.Refresh();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

如您所见,非常简单,此方法获取文件路径。像C:\Windows\notepad.exe

现在我希望 TreeView 像 FileSystem 一样显示它。

-C:\
    +Windows

如果我单击“+”,它会变成这样:

-C:\
    -Windows
       notepad.exe

这是我现在通过将这些路径发送到上述方法得到的结果:

树视图当前外观

我该怎么做才能安排节点?

4

4 回答 4

1

如果我是你,我会使用string.Split方法将输入字符串拆分为子字符串,然后搜索正确的节点以插入节点的相关部分。我的意思是,在添加节点之前,您应该检查节点 C:\ 及其子节点 (Windows) 是否存在。

这是我的代码:

...
            AddString(@"C:\Windows\Notepad.exe");
            AddString(@"C:\Windows\TestFolder\test.exe");
            AddString(@"C:\Program Files");
            AddString(@"C:\Program Files\Microsoft");
            AddString(@"C:\test.exe");
...

        private void AddString(string name) {
            string[] names = name.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
            TreeNode node = null;
            for(int i = 0; i < names.Length; i++) {
                TreeNodeCollection nodes = node == null? treeView1.Nodes: node.Nodes;
                node = FindNode(nodes, names[i]);
                if(node == null)
                    node = nodes.Add(names[i]);
            }
        }

        private TreeNode FindNode(TreeNodeCollection nodes, string p) {
            for(int i = 0; i < nodes.Count; i++)
                if(nodes[i].Text.ToLower(CultureInfo.CurrentCulture) == p.ToLower(CultureInfo.CurrentCulture))
                    return nodes[i];
            return null;
        }
于 2011-07-06T18:48:29.023 回答
0

如果您使用的是Windows 窗体(我猜是这样),您可以实现IComparer该类并使用TreeView.TreeViewNodeSorter属性:

public class NodeSorter : IComparer
{
    // Compare the length of the strings, or the strings
    // themselves, if they are the same length.
    public int Compare(object x, object y)
    {
        TreeNode tx = x as TreeNode;
        TreeNode ty = y as TreeNode;

        // Compare the length of the strings, returning the difference.
        if (tx.Text.Length != ty.Text.Length)
            return tx.Text.Length - ty.Text.Length;

        // If they are the same length, call Compare.
        return string.Compare(tx.Text, ty.Text);
    }
}
于 2011-07-06T18:39:04.013 回答
0

是父母和孩子没有区别的问题吗?

树中的每个节点也有一个 Nodes 属性,表示其子节点的集合。您的 AddNode 例程需要更改,以便您可以指定要向其添加子节点的父节点。像:

TreeNode parent = //some node
parent.Nodes.Add(newChildNode);

如果您希望它仅填充路径并找出父子关系本身,您将不得不编写一些代码来解析路径,并根据路径段识别父节点。

于 2011-07-06T18:40:41.100 回答
0

试着看看这个Filesystem TreeView。它应该完全符合您的要求。

于 2011-07-06T18:49:42.647 回答