簡體   English   中英

如何從TreeView中的節點的所有父節點獲取文本?

[英]How to get Text from all Parent Nodes of a Node in TreeView?

也許我不能很好地解釋,但這應該可以解釋:我有一個名為getParentNode(TreeNode)的int字段,以獲取它擁有多少個父對象(例如,如果節點下面有2個節點,則計數為2),並且我有一個列表名為getParentNames(TreeNode)的字段,該字段返回所有父級名稱。

getParentCount:

int getParentCount(TreeNode node)
{
    int count = 1;
    while (node.Parent != null)
    {
        count++;
        node = node.Parent;
    }
    return count;
}

getParentsNames:

List<string> getParentNames(TreeNode node)
{
    List<string> list = new List<string>();
    for (int i = 0; i < getParentCount(node); i++)
    {
        //i = 1 : list.Add(node.Parent.Text);
        //i = 2 : list.Add(node.Parent.Parent.Text);
        //i = 3 ...
    }
    return list;
}

我是否需要檢查(i == 0)(我不想手動寫,因為數字可以是任何東西)或其他東西? 問候。

為什么不使用node.FullPath計算TreeView.PathSeparator char? 就像是

char ps = Convert.ToChar( TreeView1.PathSeparator);
int nCount = selectedNode.FullPath.Split(ps).Length;

您可以使用以下任一選項:

  • 通過樹的PathSeparator分隔FullPath拆分節點的PathSeparator
  • 祖先和祖先和自擴方法


通過樹的PathSeparator分隔FullPath拆分節點的PathSeparator

您可以使用TreeNode FullPath屬性,並使用TreeView PathSeparator屬性拆分結果。 例如:

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

祖先和祖先和自擴方法

您還可以獲取TreeNode所有祖先。 您可以簡單地使用while循環來使用node.Parent而parent不為null。 我更喜歡將此邏輯封裝在擴展方法中,並使其在將來可重用。 您可以創建擴展方法以返回節點的所有父節點(祖先):

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();

您可以從祖先那里獲得文本或任何其他財產:

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

注意

JFYI您也可以使用擴展方法來獲取所有子節點。 在這里,我為此共享了一個擴展方法: Descendants Extension Method

無論如何,我注意到我需要使用while循環:

List<string> getParentNames(TreeNode node)
    {
        List<string> list = new List<string>();
        int count = getParentCount(node);
        int index = 0;
        TreeNode parent = node;
        while (index < count)
        {
            if (parent != null)
            {
                index++;
                list.Add(parent.Text);
                parent = parent.Parent;
            }
        }
        return list;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM