如何在树视图Access / VBA中上下移动Root节点

时间:2011-08-29 21:49:28

标签: ms-access vba treeview access-vba nodes

确定。我一直在树视图上工作很多,我认为允许用户上下移动树视图的节点会很方便,但他们认为合适。我的结构只是一个简单的两级树视图,但每个根节点都必须有一个子节点。例如:

Root
  child
  child
  child
Root
  child
  child
Root
  child
  child
  child
  child

我编写了代码,您一次只能从Root节点中选中一个框。我想要做的是点击一个按钮,让检查过的根节点向上(或向下)移动一个位置(当然带着它的孩子)。

我能想象这个工作的唯一方法是完全重建比以前高一级的节点。当节点开始有更多的孩子等时,这似乎太费时了。

当我搜索时,我发现了大量的C#结果,但由于我使用VBA,它根本没有帮助我。如果有人在重建整个节点之外有任何建议,我很乐意听到。感谢

1 个答案:

答案 0 :(得分:0)

我解决这个问题的方法是将我的节点的键和文本保存在临时变量中,清除键,然后切换它们。

此时,我遍历所有子节点并将它们添加到节点数组中。我将每个的nodes.Parent属性设置为对方节点,然后完成所有操作。

这是可能的,因为表中的数据取决于用户如何构建树视图,因此一旦他们让树视图显示他们想要的方式,我就可以保存我需要的信息并在他们打开特定记录时重建它起来。我希望这很清楚但我在下面有一些代码块来帮助清除它。

 Private Sub MoveUP()
 Dim n As Node
 Dim key1 As String
'etc.....

 key1 = n.Key
 text1 = n.Text
 key2 = n.Previous.Key
 text2 = n.Previous.Text

'We have to clear out the keys now.
 n.Key = ""
 n.Previous.Key = ""

'Now replace the keys
 n.Key = key2
 n.Text = text2
 n.Previous.Key = key1
 n.Previous.Text = text1

 Call SwitchParents(n, n.Previous)
 End Sub

^上面的代码是将n向上移动到n.Previous spot 以下代码是切换节点的子节点(如果有的话)

 Private Sub SwitchParents(n1 As Node, n2 As Node)
 Dim nds1() As Node 'Declare with no size to ReDim later
 Dim nds2() As Node
 Dim c As Node 'this is the child node we will use to push into the array
 Dim i As Integer 

 i = n1.Children
 ReDim nds1(0 To i)
 Set c = n1.Child
 'Notice in both loops that i remains the number of children, the arrays fill backwards
 'because when you reassign the nodes.Parent property, the node jumps to the beginning,
 'so we pack them backwards and they come out displaying the same way they did before.
 Do While Not (c Is Nothing)
   i = i - 1
   Set nds1(i) = c
   Set c = c.Next
 Loop

 i = n2.Children
 ReDim nds2(0 To i)
 Set c = n2.Child
 Do While Not (c Is Nothing)
   i = i - 1
   Set nds2(i) = c
   Set c = c.Next
Loop

If Not IsEmpty(nds1()) Then
  For i = 0 To UBound(nds1()) - 1
    Set nds1(i).Parent = n2
  Next i
End If

If Not IsEmpty(nds2()) Then
  For i = 0 To UBound(nds2()) - 1
    Set nds2(i).Parent = n1
  Next i
End If
End Sub

我希望这个例子可以帮助其他拥有类似两级树结构的人,并希望做到这样的事情。我是按下按钮进行的​​,但是可以通过拖放方法对其进行重新设计。