I am trying to create a TreeView nested structure with the use of self referencing table fields. Here is a simple example:
Category 1
Product 1
Toy 1
Toy 2
Product 2
Toy 3
Toy 4
more categories..
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.
I am using the following code but it does not generate the TreeView (ASP.NET) successfully.
public void BuildTree(List<Category> 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<Category>(), tnAdd);
}
else
{
tnAdd = new TreeNode();
tnAdd.Text = category.Description;
BuildTree((from c in categories
where c.ParentCategoryId == category.CategoryId
select c).ToList<Category>(), tnAdd);
}
if (tnAdd != null)
treeNode.ChildNodes.Add(tnAdd);
}
}
Does this require recursion!
and here is the result I get:
80W
40W
40W
Light Bulbs
Flourecent
Incedecent
60W
80W
60W
Flourecent
40W
80W
60W
Incedecent
80W
40W
60W
What isn’t successful?
If its because you see nothing … I don’t see where you’re ever adding the root node to the actual tree control. tnAdd needs to be added to the tree control somewhere.
If it’s because your not getting everything you expect: Unless you already have recursion going on somewhere and don’t realize it, I can’t see how the above code is ever going to get to the toy level. You say “base”, then “child” in the above code which covers two levels. You have three levels in your sample data, so at some point you need to account for adding the toys. You can write it recursively if you need to have n levels. If you only have three levels, you can just repeat yourself.
—– UPDATES FOR OP UPDATES
Looking at your code, what you have is this:
This means every item is hit in the first foreach and added to the tree, rather than per level.
what you want is
Something closer to this (I don’t have time to test right now, sorry) should come close to working