Populating Treeview with Linq

I play with Linq-SQL and want to display my data in a TreeView in a form. I also use .net 3.5 if that matters.

Now, my question is, is there a better way to populate this tree? Now I do it like this (psuedo):

for each order { OrderNode = new TreeViewNode for each product in order { ProductNode = new TreeViewNode OrderNode.Add(ProductNode) } OrdersTreeView.Add(OrderNode) } 

Thanks in advance!

0
source share
1 answer

Here is a rough way to create nodes given by recursion (in perfect mash, semi-psuedo)

 private void CreateNodeAndInvestigateChildrenOfNode(HierarchyData data) { //does this node have children??? if (data.HasChildren) { //get children IEnumerable<ChildRecord> childUsers = GetChildRecordsForData(data); foreach (child in childUsers) { HierarchyData newNode = new HierarchyData (); newNode.ParentNode = data; newNode.ThisData = child; data.ChildNodes.Add(newNode); CreateNodeAndInvestigateChildrenOfNode(newNode); } } } 

Find your node root and call the method.

If you use the IHierarchyData and IHierarchicalEnumerable interfaces and create nodes with classes that implement them, treenode will accept this as a direct data source.

+2
source

Source: https://habr.com/ru/post/893049/


All Articles