开发者

C# Getting List of Directories Using TreeView Node Information

I have couple of nodes in a Tree-view that user can drag to create child nodes etc.

I am using couple of methods to retrieve the parent node list:

private static IList<Node> BuildParentNodeList(AdvTree treeView)
    {
        IList<Node> nodesWithChildren = new List<Node>();

        foreach (Node 开发者_C百科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);
        }
    }

Then, on the parent node I use an extension method to get all the descendant nodes:

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;
        }
    }

Here's a typical arrangement of my nodes:

Computer
  Drive F
    Movies     
    Music
      Enrique
      Michael Jackson
        Videos

I need a string representation of the path of every node that has child nodes. 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

I am having problem getting this exact representation using the above methods. Any help will be much appreciated. Thanks.


This worked for me:

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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜