日期:2014-05-17  浏览次数:21116 次

根据Treenode全路径如何生成完整的Treeview树?
根据数据库中保存的几个节点路径,要在Winform界面上的Treeview上显示完整的树。
保存的数据类似:
Flowmaster
Flowmaster\\network1
Flowmaster\\network2
Flowmaster\\project1
Flowmaster\\project1\\network3
Flowmaster\\project2
Flowmaster\\project2\\network4

要形成的树结构:
Flowmaster
  network1
  network2
  project1
     network3
  project2
     network4

憋了半天这个算法都么弄出来,各位帮忙看下
Treenode

------解决方案--------------------

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        SetupControls();
    }

    public void SetupControls()
    {
        string[] data =
        {
            "Flowmaster",
            "Flowmaster\\network1",
            "Flowmaster\\network2",
            "Flowmaster\\project1",
            "Flowmaster\\project1\\network3",
            "Flowmaster\\project2",
            "Flowmaster\\project2\\network4"
        };
        CreateTree(data);
    }
    public void CreateTree(string[] data)
    {
        string[] roots = data.Select(a => a.Split('\\')[0]).Distinct().ToArray();
        foreach (string path in roots)
        {
            TreeNode root = new TreeNode();
            root.Text = path;
            root.Name = path;
            CreateSubTree(data, root);
            treeView1.Nodes.Add(root);
        }
    }
    public void CreateSubTree(string[] data, TreeNode parent)
    {
        string[] childs =data.