Private Sub RemoveUselessFolders(inputnode as TreeNode)
Dim i as integer
For i= inputNodes.Count -1 to 0 Step -1
With inputNodes(i)
If .ImageIndex < 2 Then
If .Nodes.Count = 0 Then
.Remove
Else
RemoveUselessFolders(inputNodes(i))
End If
End If
End With
Next i
End Sub
Note i would not rely on .ImageIndex < 2 to index a folder the link is too weak and can easily be
broken. Either subclass the treenode to make a DirectoryTreeNode or create an Enum
Public Enum NodeType As Integer
Directory = 1
File = 2
End Enum
On creating the nodes set inputNode.Tag = NodeType.Directory such that this
If .ImageIndex < 2 Then
statement becomes
If ctype(.ImageIndex.Tag, NodeType) = NodeType.Directory Then
Another thing to think about is why do first fill the tree with a bunch of nodes that you then
prune. Why not do the check as you are adding th nodes such that you dont add them if
inputNodes(i).Nodes.Count = 0 ?
hth
Richard
"Marina" <so*****@nospam.com> wrote in message news:uL**************@TK2MSFTNGP14.phx.gbl...
You shouldn't modify a collection while using the foreach loop to iterate
through it because that uses an enumerator under the hood which cannot work
correctly if the collection it is going through is being modified while it
is used.
Use another type of loop.
"you" <yo*@me.com> wrote in message
news:MP************************@news.microsoft.com ... Ok, I hope that I can 'splain this right. I am very new so bear with me.
I have a treeview with its main node being a user selected folder. In
this treeview you can only see subfolders and two specific file types.
What I am trying to do next is to remove any subfolders from the tree
that bo not have any of the two file types. This is done to somewhat
unclutter the tree.
Here is my code so far to clear the folders out. It is called with the
topmost node as the inputnode to start with.
Private Sub RemoveUselessFolders(inputnode as TreeNode)
Try
Dim node As TreeNode
For Each node In inputnode.Nodes
If node.ImageIndex < 2 Then 'it is a folder
If node.Nodes.Count = 0 Then 'it has no subfolders-can remove
node.Remove
Else
RemoveUselessFolders(node)
End If
End If
Next
Catch ex As system.NullReferenceException
End Try
End Sub
This seems to throw NullReferenceException's and maybe deletes a folder
and maybe not. I just do not understand why this does not work. I do not
have VS, so I can not step through it and see what is (or isn't)
happening. Anyone have a clue?
If you need more info please let me know.
Thanks,
Jason