Reputation: 2261
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);
}
}
Upvotes: 1
Views: 8719
Reputation: 2261
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);
}
}
Upvotes: 0
Reputation: 21
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
Upvotes: 2
Reputation: 67898
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.
Upvotes: 0