c#使用TreeView节点信息获取目录列表
本文关键字:列表 获取 信息 使用 TreeView 节点 | 更新日期: 2023-09-27 18:09:29
我在树视图中有两个节点,用户可以拖动它们来创建子节点等。
我使用两个方法来检索父节点列表:
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
我需要有子节点的每个节点的路径的字符串表示形式。例句:
Computer'DriveF
Computer'DriveF'Movies'
Computer'DriveF'Music'
Computer'DriveF'Music'Enrique
Computer'DriveF'Music'Michael Jackson
Computer'DriveF'Music'Michael Jackson'Videos
我有问题得到这个确切的表示使用上述方法。任何帮助都将不胜感激。谢谢。
这对我有用:
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);
}