执行此代码将展开根目录下的所有主要节点。
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();
}
我试着在 foreach 中添加:
if (tn.Level == 1)
tn.Expand();
但这不是解决方案。
也许我需要 foreach
中的 foreach
?
所有这些代码都是在 BackgroundWorker
下工作的方法的一部分,该方法以递归方式获取我的 FTP 服务器目录和文件的列表。
因此在实时获取目录和添加节点时我想扩展节点级别。
最佳答案
因为数据结构是递归的,恕我直言,处理这个问题最合适的方法是递归遍历它。像这样:
void ExpandToLevel(TreeNodeCollection nodes, int level)
{
if (level > 0)
{
foreach (TreeNode node in nodes)
{
node.Expand();
ExpandToLevel(node.Nodes, level - 1);
}
}
}
你可以这样调用它:
ExpandToLevel(treeView1.Nodes, 1);
那只会扩展第一层。通过2扩展前两层等。
关于c# - 如何设置展开多少层TreeView节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27309068/