how to merge same paths in treeView?

itaydi

Member
Joined
Jan 26, 2011
Messages
6
Programming Experience
1-3
Hello,

I have a treeView Control with some same paths that need to be merged as in follow example:

current situation:
p1->c1->gc1->xxx
p1->c1->gc1->yyy
p1->c1->bbb

wanted situation:
p1->c1->bbb, gc1->xxx, yyy

how do I do that in vb.net code.

tnx in advanced,
Itay
 
You can check when adding nodes if a key (TreeNode.Name) exist. When using the .Nodes(key As String) property it either return the existing node or Nothing if no node by that key exist.
 
thanx, but I want to merge paths not nodes.

Thank you JohnH for the quick answer, but it doesn't quite solve my problem.

for example, there can be two diffrent nodes with same named child.
I allow multiple nodes with same name but not as two childs of same node.

any more ideas?
 
That is not a problem, because they will not belong to same TreeNodeCollection. Each node in TreeView has it's own TreeNodeCollection represented with its Nodes property.
 
I managed it by myself

hi JohnH
I got this right
and the code for bulding a tree from xml merging similar paths is as follow:

private sub buildTreeFromXML(byval xmlFilePath as string, byval trv as TreeView)
dim xmlDoc as new xmlDocument
xmlDoc.load(xmlFilePath)
trv.Nodes.Clear()
addTreeNodes(trv.Nodes, xmlDoc.DocumentElement)
end sub

Private sub addTreeNodes(byval parentNodes as TreeNodesCollection, byval xmlNode as xmlNode)
For Each childNode as XmlNode in xmlNode.ChildNodes
if Not parentNodes.ContainsKey(childNode.Name) Then
Dim newNode as TreeNode = parentNodes.Add(childNode.Name)
newNode.Name = childNode.Name
addTreeNodes(newNode.Nodes, childNode)
else
addTreeNodes(parentNodes(parentNodes.IndexOfKey (childNode.Name)).Nodes, childNode)
end if
Next
End Sub


Thanx very much for the quick help!
 
or simplified as indicated:
VB.NET:
For Each ...
    Dim node As TreeNode = parentNodes(childNode.Name)
    If node Is Nothing Then
        node = parentNodes.Add(childNode.Name, childNode.Name)
    End If
    addTreeNodes(node.Nodes, childNode)
Next
This may again be simplified using the If operator with two arguments:
VB.NET:
For Each ...
    Dim node As TreeNode = If(parentNodes(childNode.Name), parentNodes.Add(childNode.Name, childNode.Name))
    addTreeNodes(node.Nodes, childNode)
Next
 
Back
Top