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

このコードは、単一の親ノードとその子ノードで機能しますが、複数の親ノードがある場合は機能しません。3 つの親ノードがある場合、それらの親ノードの 1 つが削除されません。

以下のようにコードを変更しました。

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

このコードを見ただけではわかりませんが、私には奇妙に見えることの1つは、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 に答える