TreeView递归绑定无限分类数据

时间:2022-11-15 23:01:33

TreeView递归绑定无限分类数据

实现一个动态绑定,无限级分类数据时,需要将数据绑定到TreeView控件,分类表的结构是这样的:

字段

类型

Id

int

ParentId

int

Name

Nvarchar(64)

实现数据绑定:

TreeView递归绑定无限分类数据

        private void ControlsDataBind()
{
tvCategory.Nodes.Clear();
List<Models.Category> types = CommonNews.Helper.OperateContext.Current.LoadNewsTypes();
IEnumerable<Models.Category> rootNodes = types.Where(t => t.ParentId == );
TreeNode node = null;
foreach (Models.Category item in rootNodes)
{
node = new TreeNode(item.CategoryName, item.CategoryId.ToString());
if (tvCategory.Nodes.Contains(node))
{
continue;
}
IEnumerable<Models.Category> ts = types.Where(t => t.ParentId == item.CategoryId);
AddNodesToTree(ts, node, );
}
} private void AddNodesToTree(IEnumerable<Models.Category> category, TreeNode node, int level)
{
TreeNode childNode = null;
foreach (Models.Category c in category)
{
childNode = new TreeNode(c.CategoryName, c.CategoryId.ToString());
if (tvCategory.Nodes.Contains(childNode))
{
continue;
}
node.ChildNodes.Add(childNode);
AddNodesToTree(category.Where(t => t.CategoryId == c.ParentId), childNode, level + );
}
tvCategory.Nodes.Add(node);
}

TreeViewBind