views:

958

answers:

2

Started to look at the Treeview control.

Is there anyway to tie the Tree View control into a Directory structure on the Web Server using Visual basic?

I have a lot of legacy files, which are updated and added often. Obviously I could code the structure in XML but this would be laborious and hard to train out to the end user.

I guess it would be a dynamic creation of an XML file perhaps?

+1  A: 

A custom sitemap provider is a good bet.

There is a good article on 4guys title "Examining ASP.NET 2.0's Site Navigation - Part 4 "

ScottE
It's a good article.
David Robbins
+1  A: 

Here's an elementary sample that I created awhile ago when learning to play with the TreeView. I have now converted the code to VB.NET using an online converter for your benefit.

It recursively walks the directory tree starting from the root of the virtual directory and creates nodes for each sub-directory or file encountered. I think this is exactly what you needed.

For visual separation, I had used icons to differentiate files from folders (folder.gif and file.gif). You can remove that parameter if you want.

Complete ASPX follows (You can paste it into a new page and it should run):


<%@ Page Language="VB" %>
<%@ Import Namespace="System.IO" %>

<script runat="server">
  Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    If Not Page.IsPostBack Then
      Dim rootDir As New DirectoryInfo(Server.MapPath("~/"))

      ' Enter the RecurseNodes function to recursively walk the directory tree. 
      Dim RootNode As TreeNode = RecurseNodes(rootDir)

      ' Add this Node hierarchy to the TreeNode control. 
      Treeview1.Nodes.Add(RootNode)
    End If
  End Sub

  Private Function RecurseNodes(ByVal thisDir As DirectoryInfo) As TreeNode
    Dim thisDirNode As New TreeNode(thisDir.Name, Nothing, "Images/folder.gif")

    ' Get all the subdirectories in this Directory. 
    Dim subDirs As DirectoryInfo() = thisDir.GetDirectories()
    For Each subDir As DirectoryInfo In subDirs
      thisDirNode.ChildNodes.Add(RecurseNodes(subDir))
    Next

    ' Now get the files in this Directory. 
    Dim files As FileInfo() = thisDir.GetFiles()
    For Each file As FileInfo In files
      Dim thisFileNode As New TreeNode(file.Name, Nothing, "Images/file.gif")
      thisDirNode.ChildNodes.Add(thisFileNode)
    Next

    Return thisDirNode
  End Function
</script>

<html>
<head>
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
      <asp:treeview ID="Treeview1" runat="server"></asp:treeview>
    </form>
</body>
</html>
Cerebrus
Sir,This is amazing, and so simple. Many many thanks
David A
It's my pleasure and you're most welcome. :-)
Cerebrus