tags:

views:

52

answers:

1

I'm trying to work out how to construct a tree view where child nodes are based on a single database table in which rows can link to other rows indicating the parent/child relationship.

For example, given the table:

ID  ID_parent  Ten
1   null       a
2   1          b
3   1          c
4   null       d
5   4          e
6   4          f

I want show follow:

a
  b
  c
d
  e
  f
+1  A: 

Without knowing your data retrieval technology or how you are going to data bind to your component I will be a generic as possible.

First thing you need to do is get the data out of the database. There are ways to do this hierarchically in sql server but in the spirit of being generic lets assume you are going to get it out as a flat structure. The important thing is your data is ordered by it's parent id, you can do this in sql or in code.

Assuming that you now have an ordered set of data we can populate our node objects. An example of this would be:

public class Node : ICollection<Node>
{
    private List<Node> childNodes;

    public Node()
    {
        childNodes = new List<Node>();
    }

    public Node this[int index]
    {
        get { return childNodes[index]; }
        set { childNodes[index] = value; }
    }

    public void Add(Node childNode)
    {
        childNodes.Add(childNode);
    }            

    /* Rest of ICollection<T> implementation */
}

Now to populate the structure you need to iterate through the original data.

public Node PopulateTree(TreeData[] treeData)
{
    Dictionary<{IdType}, Node> flattenedTree = new Dictionary<{IdType}, Node>();

     foreach(TreeData data in treeData)
     {
         Node node = new Node();

         if (data.ParentId != {EmptyId})
         {
             Node parentNode = flattenedTree[data.ParentId];
             parentNode.Add(node);
         }

         flattenedTree.Add(data.Id, node);
     }
}

I have not tested the pseudo code but it should show you a way of getting flattened data into a hierarchical structure. You should be able to refactor this down to a cleaner structure but how depends on your code base.

Bronumski
Thanks! I will do it now.
Vuong Mao