【问题标题】:Arrange TreeView by getting file paths?通过获取文件路径来排列 TreeView?
【发布时间】:2011-07-06 18:28:51
【问题描述】:

我有这个代码:

    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

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

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

【问题讨论】:

标签: c# .net winforms treeview treenode


【解决方案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;
        }

【讨论】:

【解决方案2】:

如果您使用的是 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);
    }
}

【讨论】:

    【解决方案3】:

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

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

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

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-14
        • 2023-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多