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
謝謝你的幫忙。我將我的代碼更改爲for循環,因爲在刪除節點之後更改了樹節點集合,因此它給出的結果不恰當。你在循環內提到語句,所以這是個大錯誤。謝謝。 – 2012-07-18 11:29:45