0

我有一个预先构建的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
4

1 回答 1

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
于 2012-07-18T10:33:09.363 回答