【发布时间】:2009-05-26 02:59:11
【问题描述】:
开始看Treeview控件。
是否可以使用 Visual basic 将 Tree View 控件绑定到 Web 服务器上的目录结构中?
我有很多旧文件,这些文件经常更新和添加。显然我可以用 XML 编码结构,但这会很费力,而且很难培训给最终用户。
我猜这可能是动态创建一个 XML 文件?
【问题讨论】:
开始看Treeview控件。
是否可以使用 Visual basic 将 Tree View 控件绑定到 Web 服务器上的目录结构中?
我有很多旧文件,这些文件经常更新和添加。显然我可以用 XML 编码结构,但这会很费力,而且很难培训给最终用户。
我猜这可能是动态创建一个 XML 文件?
【问题讨论】:
这是我不久前在学习使用 TreeView 时创建的一个基本示例。为了您的利益,我现在使用online converter 将代码转换为 VB.NET。
它从虚拟目录的根开始递归地遍历目录树,并为遇到的每个子目录或文件创建节点。我认为这正是您所需要的。
为了视觉分离,我使用图标来区分文件和文件夹(folder.gif 和 file.gif)。如果需要,您可以删除该参数。
完整的 ASPX 如下(您可以将其粘贴到新页面中,它应该会运行):
<%@ 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>
【讨论】:
自定义站点地图提供商是不错的选择。
有一篇关于 4guys 标题“检查 ASP.NET 2.0 的站点导航 - 第 4 部分”的好文章
【讨论】: