我在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中真实显示的节点遍历出来呢?

解决方案 »

  1.   

    用递归的方法遍历,不要用For   each   in了我给你贴两段代码。你看看。   
        
        
      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   
        
        
      

  2.   

    感谢楼上的回复。
    你的方法还是要自己指定"Root1","Root2","Root3"这些根节点,再去用递归遍历呀。
    我的根节点都是不确定的,有没有办法在不用For  each  in的情况下,直接从根节点开始遍历呢?
      

  3.   

    我在For  each  in获取根节点后用的是递归方法来遍历的,只是For  each  in获取出来的节点顺序有问题Public Sub Traval(nodeX As Node)
        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
      

  4.   

    这种代码很多呀,网上去查查能找的到.
    www.codesky.com/vb
      

  5.   

    VB的例子中有一个关于treeview的操作中有这个操作,找找看。
      

  6.   

    TreeView 的节点结构可以看成一棵二叉树:下一个兄弟可以看成左节点,第一个儿子可以看成右节点。
    只要找到根节点(第1层的第1个节点),那么遍历二叉树的方法在任意一本数据结构的教材中都有。找根节点:
    1)任取一个节点,比如 n = Nodes(1)
    2)循环:如果 n.Parent 存在,则 n = n.Parent
    3)循环:如果 n.Previous 存在,则 n = n.Previous 
    最后 n 就是根节点。