[英]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.