且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从TreeView中的节点的所有父节点获取文本?

更新时间:2023-02-05 20:13:59

您可以使用以下任一选项:

You can use either of these options:

  • 通过树的 PathSeparator 拆分节点的 FullPath
  • 祖先和AncestorsAndSelf扩展方法


您可以使用 TreeNode FullPath 属性,并使用 TreeView PathSeparator 属性拆分结果.例如:

You can use FullPath property of the TreeNode and split the result using PathSeparator property of TreeView. For example:

private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
    var ancestorsAndSelf = e.Node.FullPath.Split(treeView1.PathSeparator.ToCharArray());
}

祖先和祖先和自扩展方法

您还可以获取 TreeNode 的所有祖先.您可以简单地使用while循环在父级不为null的情况下使用 node.Parent 向上跳转.我更喜欢将此逻辑封装在扩展方法中,并使其在将来可重用.您可以创建扩展方法以返回节点的所有父节点(祖先):

Ancestors and AncestorsAndSelf sxtension methods

Also you can get all ancestors of a TreeNode. You can simply use a while loop to go up using node.Parent while the parent is not null. I prefer to encapsulate this logic in an extension method and make it more reusable for future. You can create an extension method to return all parent nodes (ancestors) of a node:

using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
public static class TreeViewExtensions
{
    public static List<TreeNode> Ancestors(this TreeNode node)
    {
        return AncestorsInternal(node).Reverse().ToList();
    }
    public static List<TreeNode> AncestorsAndSelf(this TreeNode node)
    {
        return AncestorsInternal(node, true).Reverse().ToList();
    }
    private static IEnumerable<TreeNode> AncestorsInternal(TreeNode node, bool self=false)
    {
        if (self)
            yield return node;
        while (node.Parent != null)
        {
            node = node.Parent;
            yield return node;
        }
    }
}

用法:

List<TreeNode> ancestors = treeView1.SelectedNode.Ancestors();

您可以从祖先那里获得文字或其他任何财产:

You can get text or any other property from ancestors:

List<string> ancestors = treeView1.SelectedNode.Ancestors().Select(x=>x.Text).ToList(); 

注意

JFYI,您也可以使用扩展方法来获取所有子节点.在这里,我分享了一个扩展方法,以便于:后代扩展方法.

JFYI you can use an extension method approach to get all child nodes too. Here I've shared an extension method to to so: Descendants Extension Method.