C#动态生成treeview目录树

思路:

  1. 获取全量树结构数据
  2. 通过递归动态添加树子节点

动态生成目录树 TreeView

在这里我第一步就无需复述了!主要是返回如下格式数据
在这里插入图片描述

//调用生成目录树方法
DepartmentTree.initDeptTree(this.deptTv.Nodes, deptList); //初始化目录树数据

//初始化 构建 部门目录数据
public static void initDeptTree(TreeNodeCollection nodes, IList<SysDeptVo> deptList)
{
    
    
	if (null!= deptList && deptList.Count>0)
	{
    
    
		for (int i=0;i< deptList.Count;i++)
		{
    
    
			TreeNode treeNode = new TreeNode();
			SysDeptVo departVo = deptList[i];
			treeNode.Tag = departVo.id;
			treeNode.Name = departVo.label;
			treeNode.Text = departVo.label;
			nodes.Add(treeNode);
			if (null!= departVo.children && departVo.children.Count>0)
			{
    
    
				addChildNode(treeNode, departVo.children);
			}
		}
	}
}

//递归添加子节点
private static void addChildNode(TreeNode treeNode, List<SysDeptVo> children)
{
    
    
	for (int i = 0; i < children.Count; i++)
	{
    
    
		TreeNode childNode = new TreeNode();
		SysDeptVo departVo = children[i];
		childNode.Tag = departVo.id;
		childNode.Name = departVo.label;
		childNode.Text = departVo.label;
		treeNode.Nodes.Add(childNode);
		if (null != departVo.children && departVo.children.Count > 0)
		{
    
    
			addChildNode(childNode, departVo.children);
		}
	}
}

亲测有效,别忘了点赞在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_16771097/article/details/120785504