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

也许我不能很好地解释,但这应该解释:我有一个名为getParentNode(TreeNode)的int字段来获取它有多少父节点(例如,如果节点下面有2个节点,count将是2)并且我有一个List名为getParentNames(TreeNode)的字段,它返回所有父名称。

getParentCount:

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

getParentsNames:

 List getParentNames(TreeNode node) { List list = new List(); 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拆分节点的PathSeparator
  • 祖先和祖先以及自我扩张的方法

通过树的PathSeparator拆分节点的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而父级不是null。 我更喜欢将此逻辑封装在扩展方法中,并使其在将来更具可重用性。 您可以创建一个扩展方法来返回节点的所有父节点(祖先):

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

用法:

 List ancestors = treeView1.SelectedNode.Ancestors(); 

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

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

注意

JFYI您可以使用扩展方法方法来获取所有子节点。 在这里,我共享了一个扩展方法: Descendants Extension Method 。

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

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

无论如何,我注意到我需要使用while循环:

 List getParentNames(TreeNode node) { List list = new List(); 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; }