繁体   English   中英

c#asp.net treeview - 除TEXT之外的所有属性

[英]c# asp.net treeview - all properties working except TEXT

当我的页面打开时,它运行此方法:

    private void PrintRecursive(TreeNode treeNode, string problemValue)
    {
        // Print the node.
        System.Diagnostics.Debug.WriteLine(treeNode.Text);

        if (treeNode.Value == problemValue.Split(':')[0])
        {
            treeNode.Checked = true;

            // Then expand the SelectedNode and ALL its parents until no parent found

            treeNode.Expand();
            while (treeNode.Parent != null)
            {
                treeNode = treeNode.Parent;
                treeNode.Expand();
            }

            if (problemValue.Contains(":"))
                treeNode.Text += problemValue.Split(':')[1];
            return;
        }
        // Print each node recursively.
        foreach (TreeNode tn in treeNode.ChildNodes)
        {
            PrintRecursive(tn, problemValue);
        }
    }

treeNode.Checked = true工作正常!

treeNode.Expand()工作得很好!

但是treeNode.Text += problemValue.Split(':')[1]; 什么也没做!

problemValue的值是"111:someproblem"

我究竟做错了什么?

你需要搬家

        if (problemValue.Contains(":"))
            treeNode.Text += problemValue.Split(':')[1];

在while语句之上。

问题是,在扩展父节点时,您正在更新treeNode的值,因此当您尝试设置treeNode的文本时,您实际上是在其中一个父节点上。

如果您想要了解如何执行此操作,请查看此前的StackOverFlow发布以及有关如何枚举TreeNodes 实现IEnumerable的其他想法

如果您想要打印TreeNodes递归查看此示例

private void PrintRecursive(TreeNode treeNode)
{
   // Print the node.
   System.Diagnostics.Debug.WriteLine(treeNode.Text);
   MessageBox.Show(treeNode.Text);
   // Print each node recursively.
   foreach (TreeNode tn in treeNode.Nodes)
   {
      PrintRecursive(tn);
   }
}

// Call the procedure using the TreeView.
private void CallRecursive(TreeView treeView)
{
   // Print each node recursively.
   TreeNodeCollection nodes = treeView.Nodes;
   foreach (TreeNode n in nodes)
   {
      PrintRecursive(n);
   }
}

如果您想以IEmumerable的方式执行此操作,请尝试以下操作

public static class Extensions
{
    public static IEnumerable<T> GetRecursively<T>(this IEnumerable collection,
        Func<T, IEnumerable> selector)
    {
        foreach (var item in collection.OfType<T>())
        {
            yield return item;

            IEnumerable<T> children = selector(item).GetRecursively(selector);
            foreach (var child in children)
            {
                yield return child;
            }
        }
    }
}

这是一个如何使用它的例子

TreeView view = new TreeView();

// ...

IEnumerable<TreeNode> nodes = view.Nodes.
    .GetRecursively<TreeNode>(item => item.Nodes);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM