In a C# Treeview, I need to remove all branches that do not contain values in a list in the leafs.
For example, I have a list { 112, 74 } and a Tree:
The Data Source is a self-joined table. So I can’t easily remove the unwanted leafs and branches.
Root
Branch1
Leaf 112
Leaf 1
Branch2
Leaf 74
Branch3
Leaf 44
Branch4
Leaf 99
I should end up with:
Root
Branch1
Leaf 112
Branch2
Leaf 74
Here is the code. It sort-of works. But the TrimTree only removes the bottom level. So I need to run this function a few times to completely remove all the empty branches. VERY inefficient.
void GetTree(ref TreeView tv)
{
DataTable dt = c.GetTable("select id, parent_id, name from tbl_self_join_tree");
tv.DataSource = new HierarchicalDataSet(dt, "ID", "Parent_ID");
tv.DataBind();
}
void TrimTree(TreeNodeCollection nodes, List<string> l)
{
TreeNode node = null;
for (int ndx = nodes.Count; ndx > 0; ndx--)
{
node = nodes[ndx - 1];
if (node.ChildNodes.Count == 0 && !l.Contains(node.Value))
nodes.Remove(node);
else
TrimTree(node.ChildNodes, l);
}
}
If I can write a better SELECT query, then I won’t need the TrimTree() function 😀
Solving this will help a LOT! Thank you so much!
It seems to me you can process parent nodes after processing child nodes. This way you can handle branches with all leafs deleted: