使用字符串创建树视图

时间:2014-03-18 09:37:25

标签: c# javascript treeview

我有一个类似于

的数组
 string[] terms = { "HR;Vocation", "Home", "Stations;Europe", 
                             "Teams;Team1", "Teams;Team2", 
                             "Teams;Team3", "Teams", "Stations;Africa", "Stations", "HR", "HR;Economy", "Stations;Asia","HR;Economy;Test" };

我想基于数组(使用C#或JavaScript)创建一个看起来像跟随的树视图。

Home
HR
   Vocation
   Economy
     Test
Stations
   Europe
   Asia
   Africa
Teams
  Team1
  Team2
  Team3

谢谢,并感谢各种建议。

1 个答案:

答案 0 :(得分:0)

凌乱的代码,但有效...

private void GenerateTreeView()
    {
        string[] terms = { "HR;Vocation", "Home", "Stations;Europe", 
                         "Teams;Team1", "Teams;Team2", 
                         "Teams;Team3", "Teams", "Stations;Africa", "Stations", "HR", "HR;Economy", "Stations;Asia","HR;Economy;Test" };
        Array.Sort(terms);

        foreach(string strTerm in terms)
        {
            string[] strSubTerm = strTerm.Split(';');
            if (strSubTerm.Length < 2)
            {
                treeView1.Nodes.Add(new TreeNode(strTerm));
            }
            else
            {
                try
                {
                    if (strSubTerm.Length > 2)
                    {
                        treeView1.FindNode(strSubTerm[0] +"/" +strSubTerm[1]).ChildNodes.Add(new TreeNode(strSubTerm[strSubTerm.Length - 1]));
                        continue;
                    }
                    treeView1.FindNode(strSubTerm[0]).ChildNodes.Add(new TreeNode(strSubTerm[strSubTerm.Length - 1]));
                }
                catch
                {

                }
            }
        }
    }

希望有所帮助