I have a datatable which i get from the databasemanager class,
and i would need to transform that data into a hierarchical structure
either binding it directly to a .net treeview control or in memory first .
i have an ID column, and a ParentID column.
what i do not know necessarily is the parent ID to start with. so first thing to do would be to find out which node is the parent ID.
what would be best practice to loop over this table and make it hierarchical
BranchId ParentId ProductCount HasBranchChildren Name
0 NULL 48 1 Categories
1 0 20 1 CategoryA
2 1 10 1 CategoryA1
3 1 8 0 CategoryA2
4 1 2 0 CategoryA3
5 2 4 0 CategoryA1.1
6 2 6 0 CategoryA1.2
7 0 28 1 CategoryB
8 7 20 0 CategoryB1
9 7 8 0 CategoryB2
this would be an example datatable
of course it will have hundreds of items, and it does not always start at the root node,
its possible that with a request a certain subset of categories is requested,
however i’ve talked with the database team and they will give me NULL on root nodes
in the above example that would be element 0 in the table ….
Step 1.
You need to create a tree structure from a table in memory from, this should be simple. Checkout this question here:
Most efficient way of creating tree from adjacency list
Here is some code for your multi root case (I did not want to modify the parent values to some bogus value, therefore the virtual root and its immediate children will have parent = null, but that doe not matter for traversing the tree, since you have Children and IsRoot):
Step 2.
Sadly MS made it difficult, by not offering a simple generic way to bind to hierarchical data. But luckily others have created code that can. Use this to bind your new tree structure to a tree view:
http://ohds.codeplex.com/
From the project homepage:
You could create you’re own custom implementation of IHierarchicalDataSource but I would strongly advise against that since this is cumbersome and error prone.
Option 2:
If you do not want to use third party user controls the checkout this generic implementation of IHierarchicalDataSource this again can be bound to any hierarchical ASP.NET control:
http://elegantcode.com/2008/04/06/aspnet-hierarchicaldatasourcet/