2010-06-25 85 views
0

我正在嘗試檢查父節點下的所有子節點,到目前爲止,代碼在樹視圖中的深度只有2-3級,而且我正在尋找全部節點不管它們有多深。有人可以對此有所瞭解。在Visual Basic中檢查父節點下的所有項目

下面是代碼:

Private Sub CheckChildNode(ByVal currNode As TreeNode) 
    'set the children check status to the same as the current node 
    Dim checkStatus As Boolean = currNode.Checked 
    For Each node As TreeNode In currNode.Nodes 
     node.Checked = checkStatus 
     CheckChildNode(node) 
    Next 
End Sub 

Private Sub CheckParentNode(ByVal currNode As TreeNode) 
    Dim parentNode As TreeNode = currNode.Parent 
    If parentNode Is Nothing Then Exit Sub 
    parentNode.Checked = True 
    For Each node As TreeNode In parentNode.Nodes 
     If Not node.Checked Then 
      parentNode.Checked = False 
      Exit For 
     End If 
    Next 
    CheckParentNode(parentNode) 
End Sub 

Private Sub treeview_AfterCheck(ByVal sender As System.Object, ByVal e As 
System.Windows.Forms.TreeViewEventArgs) Handles treeview.AfterCheck 
RemoveHandler treeview.AfterCheck, AddressOf treeview_AfterCheck 
    CheckChildNode(e.Node) 
    CheckParentNode(e.Node) 
    AddHandler treeview.AfterCheck, AddressOf treeview_AfterCheck 
End Sub 
+2

可以更好地格式化代碼;-) – 2010-06-25 15:09:15

+0

重複從:http://stackoverflow.com/questions/2370420/treeview-check-and-uncheck – 2010-06-25 15:10:22

回答

0

爲了讓所有的子節點,無論他們有多麼深,你肯定需要遞歸。

也就是說,你需要一個節點的每個直接子節點並對該節點進行檢查。而且您還調用該方法來檢查每個孩子的子節點。

所以在這裏僞代碼。

node getParentNode(node child){ 
return child.parent 
} 

node checkNode(node n){ 
// perform check here for node n 
if n is not valid { 
    return false! 
} 
// do children recursively 
for each child in n.children{ 
    // function calls itself! 
    checkNode(child) 
} 
} 

Here是vb.net的遞歸教程。 Hereherehere是你可以找到更多的信息。

+0

檢查所有節點的另一種方法是將此代碼插入到您的AfterCheck statment。 私人小組myTree_AfterCheck(BYVAL發件人爲對象,BYVALË作爲System.Windows.Forms.TreeViewEventArgs)處理tvFiles.AfterCheck 昏暗T作爲樹節點 對於每個t在e.Node.Nodes t.Checked = e.Node。已選中 Next End Sub – jpavlov 2010-06-28 12:58:54

相關問題