我在TreeView控件(tvEditData)中用下述代码添加了节点。如果当前选中节点有父节点,就在当前选中节点父节点前插入新节点。如果没有父节点就在当前选中节点前插入新节点
If tvEditData.SelectedItem.Parent Is Nothing Then
Set Nod = tvEditData.Nodes.Add(tvEditData.SelectedItem.Index, tvwPrevious, , txtPath.Text, 1, 3)
Else
Set Nod = tvEditData.Nodes.Add(tvEditData.SelectedItem.Parent.Index, tvwPrevious, , txtPath.Text, 1, 3)
End If再用 For Each nodeX In tvEditData.Nodes 来遍历TreeView,发现在遍历后新添加的节点顺序与TreeView中显示的不符,新节点都出现在for循环的最后。请问要如何处理才能将TreeView中真实显示的节点遍历出来呢?
If tvEditData.SelectedItem.Parent Is Nothing Then
Set Nod = tvEditData.Nodes.Add(tvEditData.SelectedItem.Index, tvwPrevious, , txtPath.Text, 1, 3)
Else
Set Nod = tvEditData.Nodes.Add(tvEditData.SelectedItem.Parent.Index, tvwPrevious, , txtPath.Text, 1, 3)
End If再用 For Each nodeX In tvEditData.Nodes 来遍历TreeView,发现在遍历后新添加的节点顺序与TreeView中显示的不符,新节点都出现在for循环的最后。请问要如何处理才能将TreeView中真实显示的节点遍历出来呢?
Sub SaveTreeView()
Open App.Path & "\BoiCiy.txt" For Output As #1
tr_save "Root1"
tr_save "Root2"
tr_save "Root3"
Close #1
End Sub
Sub tr_save(tr As String)
On Error Resume Next
Dim nods As Node
If Tv1.Nodes(tr).Children > 0 Then
Set nods = Tv1.Nodes(tr).Child
For i = 1 To Tv1.Nodes(tr).Children
Print #1, nods.Parent.Key & "," & nods.Key & "," & nods.Text & "," & nods.Image
If nods.Children > 0 Then tr_save nods.Key
Set nods = nods.Next
Next
End If
End Sub
-------------BoiCiy.txt-------------
Root1,T1,我的伊兰特,2
T1,G3060107373,藏A88886 ,3
Root1,T3,货运,2
T3,T2,单位车,2
T2,G3050314052,藏A12351,3
T2,G3041213236,藏A12349,3
T2,G3041206151,藏A12348,3
T3,G3050314022,藏A12350,4
T3,G3060322074,藏A12345,4
T3,G3041206104,藏A12346,4
Root1,T4,危货,2
T4,G3060322075,藏A12353,5
T4,G3041206144,藏A12347,5
Root2,T5,朋友车,2
T5,G8060322072,张,3
你的方法还是要自己指定"Root1","Root2","Root3"这些根节点,再去用递归遍历呀。
我的根节点都是不确定的,有没有办法在不用For each in的情况下,直接从根节点开始遍历呢?
Dim count As Integer
Dim ChildNode As Node
Dim i As Integer count = nodeX.Children
If count > 0 Then
Set ChildNode = nodeX.Child
Traval ChildNode
For i = 2 To count
Set ChildNode = ChildNode.Next
Traval ChildNode
Next
End If
End Sub
www.codesky.com/vb
只要找到根节点(第1层的第1个节点),那么遍历二叉树的方法在任意一本数据结构的教材中都有。找根节点:
1)任取一个节点,比如 n = Nodes(1)
2)循环:如果 n.Parent 存在,则 n = n.Parent
3)循环:如果 n.Previous 存在,则 n = n.Previous
最后 n 就是根节点。