我想创建一个使用自引用表字段的TreeView嵌套结构。下面是一个简单的例子:使用自引用表创建TreeView嵌套结构表
Category 1
Product 1
Toy 1
Toy 2
Product 2
Toy 3
Toy 4
多个类别..
数据库表有称为 “A类” 单表。 ParentCategoryId指向父类别。因此,对于类别1,ParentCategoryId为空,因为它是父级。对于产品1,ParentCategoryId是类别1的id,对于玩具1,ParentCategoryId是产品1的id。
我使用下面的代码,但它不能成功生成TreeView(ASP.NET)。
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);
}
}
这是否需要递归!
和下面是结果我得到:
80W
40W
40W
Light Bulbs
Flourecent
Incedecent
60W
80W
60W
Flourecent
40W
80W
60W
Incedecent
80W
40W
60W
感谢您的答复!我更新了我的帖子!我认为在主要应用中它可以达到n级。 – 2010-06-04 16:41:49
你是个天才! – 2010-06-07 16:26:04
还有一个帮助!我需要隐藏treeview控件的根节点。 – 2010-06-07 16:39:35