2012-07-18 83 views
0

我有一个预建的TreeView控件。我想根据保存在数据库中的值将这些节点作为权限集移除。我使用递归方法删除节点,但有些节点仍然存在,不会被删除。这里是我的代码:在递归函数中移除TreeView中的多个节点

Private Sub setNodes() 
    For Each nd As TreeNode In TreeView1.Nodes 
     If nd.Name = "Students" AndAlso row.Item("CanAddStudents") = False AndAlso row.Item("CanViewStudents") = False AndAlso row.Item("CanImportStudents") = False Then 
      nd.Remove() 
      nd.Tag = False 
     End If 
     If Not nd.Tag = False Then 
      setNodes(nd) 
     End If 
     nd.Tag = True 
    Next 
End Sub 

Private Sub setNodes(ByVal nd As TreeNode) 
    For Each childNd As TreeNode In nd.Nodes 
     If childNd.Name = "Registration" AndAlso row.Item("CanAddStudents") = False Then 
      childNd.Remove() 
      childNd.Tag = False 
     ElseIf childNd.Name = "View_Registration" AndAlso row.Item("CanViewStudents") = False Then 
      childNd.Remove() 
      childNd.Tag = False 
     ElseIf childNd.Name = "Import_Student" AndAlso row.Item("CanImportStudents") = False Then 
      childNd.Remove() 
      childNd.Tag = False 
     End if 
    Next 
    If Not childNd.Tag = False Then 
     setNodes(childNd) 
    End If 
    childNd.Tag = True 
End Sub 

此代码工作在单父节点及其子节点,但是当有超过1个父节点这是行不通的。如果有3个父节点,那么其中一个父节点不会被删除。

我改变了我的代码如下。

Private Sub RemoveNodes(ByVal nc As TreeNodeCollection) 
    For i As Integer = nc.Count - 1 To 0 Step -1 
     If nc(i).Nodes.Count > 0 Then 
      RemoveNodes(nc(i).Nodes) 
     End If 
     If nc(i).Name = "Registration" AndAlso row.Item("CanAddStudents") = False Then 
      nc.RemoveAt(i) 
     ElseIf nc(i).Name = "View_Registration" AndAlso row.Item("CanViewStudents") = False Then 
      nc(i).Remove() 
     ElseIf nc(i).Name = "Import_Student" AndAlso row.Item("CanImportStudents") = False Then 
      nc(i).Remove() 
     ElseIf nc(i).Name = "Students" AndAlso row.Item("CanAddStudents") = False AndAlso row.Item("CanViewStudents") = False AndAlso row.Item("CanImportStudents") = False Then 
      nc(i).Remove() 
     End If 
    Next 
End Sub 

回答

0

很难仅通过查看这些代码的说法,但有一点,它看起来很奇怪,在我看来,在setNodes(TreeNode)方法,你只需要它自称递归的最后一个子节点。如果您想要为每个节点执行此操作,则需要将底部的If语句上移到您的For循环中。例如:

For Each childNd As TreeNode In nd.Nodes 
    If childNd.Name = "Registration" AndAlso row.Item("CanAddStudents") = False Then 
     childNd.Remove() 
     childNd.Tag = False 
    ElseIf childNd.Name = "View_Registration" AndAlso row.Item("CanViewStudents") = False Then 
     childNd.Remove() 
     childNd.Tag = False 
    ElseIf childNd.Name = "Import_Student" AndAlso row.Item("CanImportStudents") = False Then 
     childNd.Remove() 
     childNd.Tag = False 
    End if 

    'Put recursive call inside loop 
    If Not childNd.Tag = False Then 
     setNodes(childNd) 
    End If 
    childNd.Tag = True 
Next 
+0

谢谢你的帮忙。我将我的代码更改为for循环,因为在删除节点之后更改了树节点集合,因此它给出的结果不恰当。你在循环内提​​到语句,所以这是个大错误。谢谢。 – 2012-07-18 11:29:45