简体   繁体   中英

Adding child nodes to Treeview Control ASP.Net

I am trying to add the child nodes to the parent nodes in a treeview control. Everything runs fine in the degbugger, they looks as if they are getting added, but all I can see is the parent nodes. Can someone shine a little light on this. Thanks.

foreach (var item in agencyListRoot)
{
     TreeNode parentNode = new TreeNode();
     TreeNode childNode = new TreeNode();

     if (item.HeirID.ToString() == "/1/")
     {
          parentNode.Text = item.AgencyName.ToString();
          tv_Agencies.Nodes.Add(parentNode);

     } 
     if (item.HeirID.ToString() == "/1/2/")
     {
         childNode.Text = item.AgencyName.ToString();
         parentNode.ChildNodes.Add(childNode);
     }
}

May be this code will helps to you..

    foreach (DataRow dr in dtTree.Select("parent_id is null")) // To get the each parent node in the table or anything else
    {
    TreeNode node = new TreeNode(dr["name"].ToString(), dr["s_no"].ToString());
    TreeView1.Nodes.Add(node); // Adding Parent node to the treeview
    string serial_no = dr["s_no"].ToString(); // store parent node value or text in an variable
    foreach(DataRow dr1 in dtTree.Select("parent_id = '"+serial_no+"'")) // To get child node of parent node
    {
        TreeNode child_node = new TreeNode(dr1["name"].ToString(), dr1["s_no"].ToString());
        node.ChildNodes.Add(child_node);// Here adding the child node to particular parent node.
    }
    }

If you want my table structure means. Create you table like this.

Thanks and Regards, Ganesh. S

Yes, the ASP.NET tree control is fickle. You need to add all the child nodes first , and then add the parent node to the tree view.

var root = new TreeNode("root");
TreeNode group = root;

So this was the solution. Not the prettiest, but it works for what I need.

foreach (var item in agencyListRoot)
{            
    if (item.HeirID.ToString() == "/1/")
    {
        group = new TreeNode(item.AgencyName.ToString());
        root.ChildNodes.Add(group);
    } 
    else if (item.HeirID.ToString() == "/1/2/")
    {
        TreeNode childNodeU = new TreeNode(item.AgencyName.ToString());
        group.ChildNodes.Add(childNodeU);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM