asp. net TreeView Recursive Loop Child Node Generates Tree Menu Instances

  • 2021-08-12 02:27:05
  • OfStack

This article illustrates the method of asp. net TreeView recursive loop child node generating tree menu. Share it for your reference, as follows:

Here, recursive loop is mainly used to obtain child nodes


/// <summary>
///  Generate root node 
/// </summary>
/// <param name="treeview"></param>
protected void BindTreeView(long ID, TreeView treeview)
{
    DataTable dt = menuLogic.GetMenu2(ID, User.Identity.Name);
    treeview.Nodes.Clear();
    DataRow[] parentrow = dt.Select("par_id=0");
    for (int i = 0; i < parentrow.Length; i++)
    {
      TreeNode rootnode = new TreeNode();
      rootnode.Text = parentrow[i]["node_name"].ToString(); //parentrow[i][3].ToString();
      rootnode.Value = parentrow[i]["ID"].ToString(); //parentrow[i][1].ToString();  Primary key 
      rootnode.Expanded = true;
      rootnode.Selected = false;
      rootnode.SelectAction = TreeNodeSelectAction.None;
      treeview.Nodes.Add(rootnode);
      CreateChildNode(rootnode, dt); //
    }
}
/// <summary>
///  Generate child nodes 
/// </summary>
/// <param name="parentNode"></param>
/// <param name="datatable"></param>
protected void CreateChildNode(TreeNode parentNode, DataTable datatable)
{
    DataRow[] rowlist = datatable.Select("par_id=" + parentNode.Value);
    for (int i = 0; i < rowlist.Length; i++)
    {
      TreeNode node = new TreeNode();
      if (datatable.Select("par_id=" + rowlist[i]["ID"].ToString().Trim()).Length > 0)
      {
        node.Text = rowlist[i]["node_name"].ToString();
        node.Value = rowlist[i]["ID"].ToString();
      }
      else
      {
        node.Text = "<a href=\"javascript:;\" onclick=\"OpenUrl('" + rowlist[i]["url"].ToString().Trim() + "',this)\">" + rowlist[i]["node_name"].ToString() + "</a>";
        node.Value = rowlist[i]["ID"].ToString();
      }
      node.Expanded = false;
      node.Selected = false;
      node.SelectAction = TreeNodeSelectAction.None;
      parentNode.ChildNodes.Add(node);
      CreateChildNode(node, datatable); // Recursive invocation 
    }
}

For more readers interested in asp. net, please check the topics of this site: "Summary of asp. net Operation json Skills", "Summary of asp. net String Operation Skills", "Summary of asp. net Operation XML Skills", "Summary of asp. net File Operation Skills", "Summary of asp. net ajax Skills" and "Summary of asp. net Cache Operation Skills".

I hope this article is helpful to everyone's asp. net programming.


Related articles: