实现一个动态绑定,无限级分类数据时,需要将数据绑定到TreeView控件,分类表的结构是这样的:
字段 |
类型 |
Id |
int |
ParentId |
int |
Name |
Nvarchar(64) |
实现数据绑定:
private void ControlsDataBind() { tvCategory.Nodes.Clear(); List<Models.Category> types = CommonNews.Helper.OperateContext.Current.LoadNewsTypes(); IEnumerable<Models.Category> rootNodes = types.Where(t => t.ParentId == 0); 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, 0); } } 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 + 1); } tvCategory.Nodes.Add(node); }
TreeViewBind
时间: 2024-10-19 22:33:22