c# - 如何设置展开多少层TreeView节点?

标签 c# .net winforms treeview

执行此代码将展开根目录下的所有主要节点。

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/

相关文章:

c# - Excel VBA 和 C# DLL : Instantiate WinForms Object can only be done once. 第二次尝试时出现错误

javascript - 将值从 HTML 控件复制到 ASP.NET 用户控件

c# - Visual Studio 报告并非所有代码路径都返回值,即使它们返回值

c# - WebBrowser 控件页面加载错误

c# - 前景窗口大小总是错误

c# - 主窗口关闭时如何重新创建 Windows 窗体应用程序

c# - 在 C# 中获取驱动类型?或查明我的驱动器是否可移动?

c# - 这个 C# 语法的名称是什么?

.net - 通过 Ajax (ASP.NET) 远程调用 WebService

c# - Windows 10 平板电脑模式下对话框显示在父级后面