Reputation: 125
Doing this code will expand all the main nodes under root.
root images files docs
But I want to make that if I change it from 0 to 1 somehow to change the level so it will expand the next level.
root images myimages files myfiles docs mydocs
foreach (TreeNode tn in treeView1.Nodes)
{
if (tn.Level == 0)
tn.Expand();
}
I tried to add in the foreach:
if (tn.Level == 1)
tn.Expand();
But that's not a solution.
Maybe I need foreach
in foreach
?
All this code is part of a method that is working under BackgroundWorker
that get a list of my FTP server directories and files recursively.
So in real time while it's getting the directories and adding the nodes I want to expand the nodes level.
Upvotes: 3
Views: 4090
Reputation: 70652
Because the data structure is recursive, IMHO the most appropriate way to deal with the issue is to traverse it recursively. Something like this:
void ExpandToLevel(TreeNodeCollection nodes, int level)
{
if (level > 0)
{
foreach (TreeNode node in nodes)
{
node.Expand();
ExpandToLevel(node.Nodes, level - 1);
}
}
}
You would call it like this:
ExpandToLevel(treeView1.Nodes, 1);
That would expand just the first level. Pass 2 to expand the first two levels, etc.
Upvotes: 12