Ana D. 0 Junior Poster in Training

Hi,

I'm binding a TreeView using the SiteMap Data. Near to each node, I have a checkbox so that the user can select the node he wants.
I need to iterate through the tree checking if the node is checked and if so, write something like: Home - Node1 - Node2; if it's not checked, go to the next node.
I'm iteration through the tree using the following method:

Protected Sub goThroughTree(ByVal node As TreeNode)
        'Do something
        If node.ChildNodes.Count > 0 Then
            For Each child As TreeNode In node.ChildNodes
                goThroughTree(child)
            Next
        End If
    End Sub

Problem: how to write "Home - Node1 - Node2" for each checked node in the tree?

Besides, I have two types of nodes, let's say typeA and typeB. I even need to write:
- if node is typeA, write typeA - Home - Node1 - Node2
- if node is typeB, write typeB - Home - Node1 - Node2

Any help would be much appreciated.

Thanks,
Ana

Dani AI

Generated

@AnaD — two straightforward ways to produce "Home - Node1 - Node2" for each checked node and to prefix it with a node type.

Build the path on demand by walking the Parent chain: when you hit a checked node, walk up collecting each node.Text, reverse that list, then join with " - ". That only constructs strings for checked nodes and is easy to read. Prefixing is trivial if you store the type in the node (use node.Value or node.Attributes["type"] when you bind the tree). Example (C#):

string BuildPath(TreeNode node)
{
    var parts = new List<string>();
    for (var cur = node; cur != null; cur = cur.Parent)
        parts.Add(cur.Text);
    parts.Reverse();
    return string.Join(" - ", parts);
}

void WalkAndPrint(TreeNodeCollection nodes)
{
    foreach (TreeNode n in nodes)
    {
        if (n.Checked)
        {
            var prefix = string.IsNullOrEmpty(n.Value) ? "" : n.Value + " - ";
            Console.WriteLine(prefix + BuildPath(n));
        }
        if (n.ChildNodes.Count > 0) WalkAndPrint(n.ChildNodes);
    }
}

If your TreeView is data-bound (SiteMapDataSource or similar), set the type into node.Value or node.Attributes during the TreeNodeDataBound event so the traversal code can read it. Minor tips: use string.Join or a StringBuilder for long paths, guard against null parents, and avoid including " - " inside node text to prevent confusing output.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.