- how do i go from a datatable to a hierarchical structure in asp.net c#
- 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
- public class Branch
- {
- public Branch()
- {
- Children = new List<Branch>();
- }
- public bool IsRoot { get; set; }
- public int? BranchId { get; set; }
- public int? ParentId { get; set; }
- public List<Branch> Children { get; set; }
- public int ProductCount { get; set; }
- public int HasBranchChildren { get; set; }
- public string Name { get; set; }
- //other data
- }
- public class BranchTreeHelper
- {
- public Branch MakeTree()
- {
- var virtualRoot = new Branch()
- {
- BranchId = null,
- ParentId = null,
- IsRoot = true
- };
- // get the data from db, just disregard the properties: Children and IsRoot flage
- List<Branch> branchList = GetDataFromDB();
- var branchDict = branchList.ToDictionary(i => i.BranchId.Value, i => i);
- foreach(var branch in branchList)
- {
- if(branch.ParentId.HasValue)
- {
- branchDict[branch.ParentId.Value].Children.Add(branch);
- }
- else
- {
- virtualRoot.Children.Add(branch);
- }
- }
- return virtualRoot;
- }
- }
- // just a concept, not tested, might have errors
- // ObjectWithHierarchy could look something like this
- class ObjectWithHierarchy
- {
- public int Id {get;set;}
- public int? ParentId {get;set;}
- public string Name {get;set;}
- }
- private void LoadTree()
- {
- // initialize your collection of objects
- List<ObjectWithHierarchy> list = new List<ObjectWithHierarchy>();
- // build the tree
- TreeView treeView = new TreeView();
- foreach (var item in list.FindAll(i => i.ParentId == null))
- {
- // create the root node
- TreeNode rootNode = new TreeNode();
- rootNode.Text = item.Name;
- rootNode.Tag = item;
- // load child nodes
- LoadChildNodes(node, list);
- // add the node to the treeview
- treeView.Nodes.Add(rootNode);
- }
- }
- private void LoadChildNodes(TreeNode node, List<ObjectWithHierarchy> list)
- {
- ObjectWithHierarchy item = node.Tag as ObjectWithHierarchy;
- foreach (var childItem in list.FindAll(i => i.ParentId == item.Id))
- {
- // create the child node
- TreeNode childNode = new TreeNode();
- childNode.Text = childItem.Name;
- childNode.Tag = childItem;
- // load children, if there are any
- LoadChildNodes(childNode, list);
- // add it to its parent nodes collection
- node.Nodes.Add(childNode);
- }
- }