以分隔符分隔的字符串到TreeView C#

时间:2013-04-24 13:14:46

标签: c# treeview delimiter treenode

我有一个像这样的输入流:

John
Peter
Vanesa
Vanesa.New
Josh
Josh.New
Josh.New.Under
...

我需要向TreeView添加节点像这样:

+Customers
   +John
   +Peter
   +Vanesa
      +New
   +Josh
      +New
         +Under
 ...

我有一个想法是用参数'。'拆分每个字符串,但是我遇到了动态加载节点的问题。也许我必须使用某种形式......

我有旧的数据库表“group”,其中包含记录ID和GroupName。充满了这些字符串。我需要创建一些类型的“地址”:John.Element或Vanesa.New.Element或Josh.New.Under.Element,其中Element是来自其他数据表的记录。数据库连接不是问题,问题是动态填充树

现在我已经完成了添加不包含'。'的字符串:

    reader = readGroups.ExecuteNonQuery();
    while(reader.Read())
    {
        string[] buff = reader.GetValue(1).ToString().Split('.');
        if (buff.Length == 1)
        {
            treeView1.Nodes[0].Nodes.Add(reader.GetValue(1));
        }
        else
        {
            //group contains '.'
        }
    }

编辑: 我还有一个问题。有这样的记录:John,John.New,John.Old,John.Older,John.Oldest ......所以当AddNodes()方法运行时,方法结尾的foreach清除John.New,John。老,John.Older节点,但他们必须进入treenode John。如果你有一些想法...

3 个答案:

答案 0 :(得分:2)

对于winforms,这是您需要的。我正在使用递归在每个父节点中添加每个子节点。我已经进行了更改,以便在开始向实际树视图添加任何节点之前创建一个唯一节点列表

            internal class TreeNodeHierachy
    {
        public int Level { get; set; }
        public TreeNode Node { get; set; }
        public Guid Id { get; set; }
        public Guid ParentId { get; set; }
        public string RootText { get; set; }
    }

    private List<TreeNodeHierachy> overAllNodeList; 

    private void AddNodes(IEnumerable<string> data)
    {
        overAllNodeList = new List<TreeNodeHierachy>();
        foreach (var item in data)
        {
            var nodeList = new List<TreeNodeHierachy>();
            var split = item.Split('.');
            for (var i = 0; i < split.Count(); i++)
            {
                var guid = Guid.NewGuid();
                var parent = i == 0 ? null : nodeList.First(n => n.Level == i - 1);
                var root = i == 0 ? null : nodeList.First(n => n.Level == 0);
                nodeList.Add(new TreeNodeHierachy
                    {
                        Level = i,
                        Node = new TreeNode(split[i]) { Tag = guid },
                        Id = guid,
                        ParentId = parent != null ? parent.Id : Guid.Empty,
                        RootText = root != null ? root.RootText : split[i]
                    });
            }

            // figure out dups here
            if (!overAllNodeList.Any())
            {
                overAllNodeList.AddRange(nodeList);
            }
            else
            {
                nodeList = nodeList.OrderBy(x => x.Level).ToList();
                for (var i = 0; i < nodeList.Count; i++)
                {

                    var existingNode = overAllNodeList.FirstOrDefault(
                        n => n.Node.Text == nodeList[i].Node.Text && n.Level == nodeList[i].Level && n.RootText == nodeList[i].RootText);
                    if (existingNode != null && (i + 1) < nodeList.Count)
                    {

                        nodeList[i + 1].ParentId = existingNode.Id;
                    }
                    else
                    {
                        overAllNodeList.Add(nodeList[i]);
                    }
                }
            }
        }

        foreach (var treeNodeHierachy in overAllNodeList.Where(x => x.Level == 0))
        {
            treeView1.Nodes.Add(AddChildNodes(treeNodeHierachy));
        }
    }

    private TreeNode AddChildNodes(TreeNodeHierachy node)
    {
        var treeNode = node.Node;
        foreach (var treeNodeHierachy in overAllNodeList.Where(n => n.ParentId == node.Id))
        {
            treeNode.Nodes.Add(AddChildNodes(treeNodeHierachy));
        }
        return treeNode;
    }


    /// <summary>
    /// Handles the Click event of the button1 control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    private void button1_Click(object sender, EventArgs e)
    {
        //SearchActiveDirectoryWithCriteria("(mailnickname=TM418)");

        var test = new List<string>
            {
                "John",
                "Peter",
                "Vanesa",
                "Vanesa.New",
                "Josh",
                "Josh.New",
                "Josh.New.Under",
                "Josh.Old"
            };

        AddNodes(test);           
    }

答案 1 :(得分:0)

这可能主要是你想要的,你还需要一些名为treeView的TreeView的xaml:

    public TreeViewItem root;

    public MainWindow()
    {
        InitializeComponent();

        root = new TreeViewItem
        {
            Header = "Customers"
        };

        treeView.Items.Add(root);

        addNode("John");
        addNode("Peter");
        addNode("Vanesa.New");
        addNode("Josh");
        addNode("Josh.New");
        addNode("Josh.New.Under");
    }

    private void addNode(string values)
    {
        var n = root;

        foreach (var val in values.Split('.'))
        {
            var isNew = true;

            foreach (var existingNode in n.Items)
            {
                if (((TreeViewItem)existingNode).Header.ToString() == val)
                {
                    n = (TreeViewItem)existingNode;
                    isNew = false;
                }
            }

            if (isNew)
            {
                var newNode = new TreeViewItem
                {
                    Header = val
                };

                n.Items.Add(newNode);

                n = newNode;
            }
        }
    }

答案 2 :(得分:0)

我遇到了同样的问题。我用这种方式解决了这个问题:

定义实现树的类:

awk '{for(i=1;i<=NF;i++){ if($i~/[0-9]*\.[0-9]*\.[0-9]*\.[0-99]*\.[0-999]*/){print $i} } }' jfinancas.txt > teste5.txt

和主要部分:

class TreeBuilder
{
    public int index,depth;
    public string text;
    public Dictionary<string,TreeBuilder> childs;
    public void addToTreeVeiw(System.Windows.Forms.TreeNode root, TreeBuilder tb) {
        foreach (string key in tb.childs.Keys) {
            System.Windows.Forms.TreeNode t = root.Nodes.Add(tb.childs[key].text);
            addToTreeVeiw(t, tb.childs[key]);

        }
    }
}

我猜结果就是你想要的:

enter image description here