rahul rahul - 2 months ago 8
C# Question

TreeViewItem adding nodes

My attempt at adding nodes to a WPF treeview programmatically is not working as expected i.e., for the code below I expected to have leaf nodes "C14-5 and "C14-6" under "C1-4" and "C2-4" whereas they appear under the root node "Level-0"

public class CSTree 
{
public class CS_TREE
{
int nodeId; int parentId, string description;
public CS_TREE(int node, int parent, string desc)
{
nodeId = node; parentId = parent; description = desc;
}
public int NodeId { get { return nodeId;}
public int ParentId { get { return parentId;}
public int Description { get { return description;}
}

private static List<CS_TREE> tree = new List<CS_TREE>() new {
new CS_TREE(1,0,"Level-0"),
new CS_TREE(2,1,"Level-1 A"),
new CS_TREE(3,1,"Level-1 B"),
new CS_TREE(4,1,"Level-1 C"),
new CS_TREE(5,4,"Level-2 C1-4"),
new CS_TREE(6,4,"Level-2 C2-4"),
new CS_TREE(7,5,"Level-3 C14-5"),
new CS_TREE(7,6,"Level-3 C24-6"),
}

public void PopulateTreeView()
{
foreach (CS_TREE cst in L_tree)
{
AddToTree(cst);
}
}

public void AddToTree(CS_TREE cst)
{
var subitem = new TreeViewItem() { Header = cst.Description, Tag = cst};
if (cst.ParentId == 0)
{
_rootNode = new TreeViewItem() { Header = cst.Description, Tag = cst };
}
else
{
TreeViewItem node = FindNode(_rootNode, cst);
if (node != null)
{
node.Items.Add(subitem);
}
else
{
_rootNode.Items.Add(subitem);
}
}
}

private TreeViewItem FindNode(TreeViewItem rootNode, CS_TREE cst)
{
TreeViewItem rv = null;
if (rootNode != null && rootNode.HasItems)
{
var items = rootNode.Items;
foreach (TreeViewItem item in items)
{
CS_TREE nodeCST = item.Tag as CS_TREE;
if (nodeCST.NodeId == cst.ParentId)
{
return item;
}
else if (item.HasItems)
{
FindNode(item, cst);
}
}
}
return rv;
}

private TreeViewItem _rootNode = null;
public TreeViewItem Root
{
get { return _rootNode; }
}


}



Could readers point me in the right direction?

Answer

You need to return the found node. So instead of

FindNode(item, cst);

do

rv = FindNode(item, cst);
if (rv != null)
    return rv;

Additionally you are using the same NodeId 7 in nodes "C14-5" and "C24-6".

So if you want any nodes under "C24-6", you should write

new CS_TREE(8,6,"Level-3 C24-6"),
Comments