Home » c# » c# – How to build a TreeView nodes with custom structure?-Exceptionshub

c# – How to build a TreeView nodes with custom structure?-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I am trying to build up a Treeview in Winform (using c#) with similar structure like the attached image.
Let say I have the Lowest node information with all their parent nodes info. For example: I have information of the lowest child node name is: “a”, it’s parent node is : “b”, then grand node is “c” and so on “d”. I will have all the lowest child nodes with all of their parents info, so need to create and gruop them in the correct group. So I just wonder how to do that ?

Thank you :).

enter image description here

How to&Answers:

You can try using Tag to keep the instance corresponds with its node, e.g.

using System.Linq;

...

private static TreeNode AddNodes<T>(TreeView tree, IEnumerable<T> items) {
  if (null == tree)
    throw new ArgumentNullException(nameof(tree));
  else if (null == items)
    throw new ArgumentNullException(nameof(items));

  bool found = true;
  TreeNodeCollection nodes = tree.Nodes;
  TreeNode node = null; 

  foreach (var item in items.Reverse()) {
    if (found) {
      node = nodes.OfType<TreeNode>().FirstOrDefault(nd => object.Equals(nd.Tag, item));

      found = node != null;
    }

    if (!found) {
      node = new TreeNode(item?.ToString());
      node.Tag = item;
      nodes.Add(node);
    }

    nodes = node.Nodes;
  }

  return node;
}

Usage:

myTreeView.BeginUpdate();

try { 
  // Items from child to parent
  AddNodes(myTreeView, new string[] { "leaf", "parent", "root"});
  AddNodes(myTreeView, new string[] { "child", "parent", "root" });
  AddNodes(myTreeView, new string[] { "child", "branch", "root" });
}
finally {
  myTreeView.EndUpdate();
}

And you’ll have

root
  parent
    leaf
    child
  branch 
    child

structure