如何从TreeView中一个节点的所有父节点获取文本
本文关键字:节点 父节点 取文本 获取 一个 TreeView | 更新日期: 2023-09-27 18:09:41
也许我不能很好地解释,但这应该解释:我有一个名为getParentNode(TreeNode)的int字段来获取它有多少父节点(例如,如果节点下面有2个节点,count将是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)(我不想手动写,因为数字可以是任何东西)或其他东西?问候。
您可以使用以下两个选项之一:
- 用树的
PathSeparator
拆分节点的FullPath
- 祖先和祖先/自扩展方法
用树的PathSeparator
拆分节点的FullPath
您可以使用TreeNode
的FullPath
属性并使用TreeView
的PathSeparator
属性拆分结果。例如:
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
var ancestorsAndSelf = e.Node.FullPath.Split(treeView1.PathSeparator.ToCharArray());
}
Ancestors和ancorsandself扩展方法
也可以得到TreeNode
的所有祖先。当父变量不为空时,您可以简单地使用一个while循环来使用node.Parent
向上运行。我更倾向于将此逻辑封装在扩展方法中,以便将来更易于重用。您可以创建一个扩展方法来返回节点的所有父节点(祖先节点):
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();
注意
仅供参考,您也可以使用扩展方法来获取所有子节点。这里我分享了一个扩展方法:Descendants extension method .
为什么不使用node.FullPath
计数TreeView.PathSeparator
字符呢?就像
char ps = Convert.ToChar( TreeView1.PathSeparator);
int nCount = selectedNode.FullPath.Split(ps).Length;
无论如何,我注意到我需要使用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;
}