我在树视图中有几个节点,用户可以拖动它们来创建子节点等。
我使用几种方法来检索父节点列表:
private static IList<Node> BuildParentNodeList(AdvTree treeView)
{
IList<Node> nodesWithChildren = new List<Node>();
foreach (Node node in treeView.Nodes)
AddParentNodes(nodesWithChildren, node);
return nodesWithChildren;
}
private static void AddParentNodes(IList<Node> nodesWithChildren, Node parentNode)
{
if (parentNode.Nodes.Count > 0)
{
nodesWithChildren.Add(parentNode);
foreach (Node node in parentNode.Nodes)
AddParentNodes(nodesWithChildren, node);
}
}
然后,在父节点上,我使用扩展方法来获取所有后代节点:
public static IEnumerable<Node> DescendantNodes(this Node input)
{
foreach (Node node in input.Nodes)
{
yield return node;
foreach (var subnode in node.DescendantNodes())
yield return subnode;
}
}
以下是我的节点的典型安排:
Computer
Drive F
Movies
Music
Enrique
Michael Jackson
Videos
我需要一个包含子节点的每个节点的路径的字符串表示。 E.g:
Computer\DriveF
Computer\DriveF\Movies\
Computer\DriveF\Music\
Computer\DriveF\Music\Enrique
Computer\DriveF\Music\Michael Jackson
Computer\DriveF\Music\Michael Jackson\Videos
我在使用上述方法获得此精确表示时遇到问题。任何帮助都感激不尽。感谢。
答案 0 :(得分:1)
这对我有用:
private void button1_Click(object sender, EventArgs e)
{
List<string> listPath = new List<string>();
GetAllPaths(treeView1.Nodes[0], listPath);
StringBuilder sb = new StringBuilder();
foreach (string item in listPath)
sb.AppendLine(item);
MessageBox.Show(sb.ToString());
}
private void GetAllPaths(TreeNode startNode, List<string> listPath)
{
listPath.Add(startNode.FullPath);
foreach (TreeNode tn in startNode.Nodes)
GetAllPaths(tn, listPath);
}