Creating a TreeView Nested Structure Using Self Referencing Table
<p>I am trying to create a TreeView nested structure with the use of self referencing table fields. Here is a simple example: </p>

<pre><code>Category 1 
      Product 1 
          Toy 1 
          Toy 2 
      Product 2 
          Toy 3 
          Toy 4 
</code></pre>

<p>more categories.. </p>

<p>The database table has a single table called "Category". The ParentCategoryId points to the Category which is the parent. So, for the Category 1 the ParentCategoryId is null since it is parent. For Product 1 the ParentCategoryId is that of the Category 1 id and for Toy 1 the ParentCategoryId is that for the Product 1 id. </p>

<p>I am using the following code but it does not generate the TreeView (ASP.NET) successfully. </p>

<pre><code> public void BuildTree(List&lt;Category&gt; categories, TreeNode treeNode)
    {
        if (treeNode == null) return;

        TreeNode tnAdd = null;
        var categoryId = Guid.NewGuid();

        foreach (var category in categories)
        {
            if (category.IsBaseCategory)
            {
                tnAdd = new TreeNode();
                tnAdd.Text = category.Description;

                BuildTree((from c in categories
                           where c.ParentCategoryId == category.CategoryId
                           select c).ToList&lt;Category&gt;(), tnAdd);
            }
            else
            {
                tnAdd = new TreeNode();
                tnAdd.Text = category.Description;

                BuildTree((from c in categories
                           where c.ParentCategoryId == category.CategoryId
                           select c).ToList&lt;Category&gt;(), tnAdd);
            }

            if (tnAdd != null)
                treeNode.ChildNodes.Add(tnAdd);              
        }
    }
</code></pre>

<p>Does this require recursion! </p>

<p>and here is the result I get: </p>

<pre><code>  80W 
  40W 
  40W 
  Light Bulbs 

   Flourecent 
   Incedecent 

  60W 
  80W 
  60W 
  Flourecent 

   40W 
   80W 
   60W 

  Incedecent 

   80W 
   40W 
   60W 
</code></pre>
