title: ASP.NET TreeView + AJAX
body: <p>I have a treeview I'm using to display a directory structure. I am trying to reduce load times by loading sub nodes on node expansion. Is there a way to do this?</p>
  
  <p>Below is the code I'm currently using to populate the treeview:</p>
  
  <pre><code>protected void Page_Load(object sender, EventArgs e) {
      BuildTree(Request.QueryString["path"]);
  }
  private void BuildTree(string dirPath)
  {
      //get root directory
      System.IO.DirectoryInfo rootDir = new System.IO.DirectoryInfo(dirPath);
  
      //create and add the root node to the tree view
      TreeNode rootNode = new TreeNode(rootDir.Name, rootDir.FullName);
      TreeView1.Nodes.Add(rootNode);
  
      //begin recursively traversing the directory structure
      TraverseTree(rootDir, rootNode);
  }
  private void TraverseTree(System.IO.DirectoryInfo currentDir, TreeNode currentNode)
  {
      //loop through each sub-directory in the current one
      foreach (System.IO.DirectoryInfo dir in currentDir.GetDirectories())
      {
              //create node and add to the tree view
              TreeNode node = new TreeNode(dir.Name, dir.FullName);
              currentNode.ChildNodes.Add(node);
  
              //recursively call same method to go down the next level of the tree
              TraverseTree(dir, node);
      }
  
      foreach (System.IO.FileInfo file in currentDir.GetFiles())
      {
          TreeNode node = new TreeNode(file.Name, file.FullName);
          currentNode.ChildNodes.Add(node);
      }
  }
  </code></pre>