C# 递归生成树(无限级)

时间:2022-06-28 12:40:43

调用

T_SubClassItem dataSubClassItem = JsonConvert.DeserializeObject<T_SubClassItem>(str); //更改为所需数据源
TreeNode root = new TreeNode();
CreateTree(root, 0, dataSubClassItem);

递归生成树

public void CreateTree(TreeNode Node, int ParentId, T_SubClassItem SubClassItem)
{
    if (ParentId == 0)
    {
        Node.Tag = SubClassItem.ID;
        Node.Text = SubClassItem.SubClassItem;
        tree.Nodes.Add(Node);
        CreateTree(Node, SubClassItem.ID, SubClassItem);
    }
    else
    {
        if (SubClassItem.children.Count != 0)
        {
            for (int i = 0; i < SubClassItem.children.Count; i++)
            {
                TreeNode node = new TreeNode();
                node.Tag = SubClassItem.children[i].ID;
                node.Text = SubClassItem.children[i].SubClassItem;
                CreateTree(node, Convert.ToInt32(SubClassItem.children[i].ParentId), SubClassItem.children[i]);
                Node.Nodes.Add(node);
            }
        }
    }
}