我試圖從我的根目錄中的一個文件夾(稱爲文件夾)構建文件和文件夾的樹視圖。Treeview在C#中不工作asp.net
我的C#代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public class Default2: Seisan.DefaultTemplate
{
protected void Page_Load(object sender, EventArgs e){
if (!this.IsPostBack){
DirectoryInfo rootInfo = new DirectoryInfo(Server.MapPath("~/Folders/"));
this.PopulateTreeView(rootInfo, null);
}
}
private void PopulateTreeView(DirectoryInfo dirInfo, TreeNode treeNode)
{
foreach (DirectoryInfo directory in dirInfo.GetDirectories())
{
TreeNode directoryNode = new TreeNode(directory.Name, directory.FullName);
if (treeNode == null)
{
TreeView.Nodes.Add(directoryNode);
}
else
{
treeNode.ChildNodes.Add(directoryNode);
}
//Get all files in the Directory.
foreach (FileInfo file in directory.GetFiles())
{
TreeNode fileNode = new TreeNode(file.Name, file.FullName, "_blank", (new Uri(Server.MapPath("~/"))).MakeRelativeUri(new Uri(file.FullName)).ToString());
directoryNode.ChildNodes.Add(fileNode);
}
PopulateTreeView(directory, directoryNode);
}
}
和我的樹視圖asp.Net代碼:
<asp:TreeView ID="TreeView" runat="server" ImageSet="XPFileExplorer" NodeIndent="15">
<HoverNodeStyle Font-Underline="True" ForeColor="#6666AA" />
<NodeStyle Font-Names="Tahoma" Font-Size="8pt" ForeColor="Black" HorizontalPadding="2px" NodeSpacing="0px" VerticalPadding="2px"></NodeStyle>
<ParentNodeStyle Font-Bold="False" />
<SelectedNodeStyle BackColor="#B5B5B5" Font-Underline="False" HorizontalPadding="0px"
VerticalPadding="0px" />
</asp:TreeView>
運行時,我得到這個錯誤:
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0120: An object reference is required for the non-static field, method, or property 'System.Web.UI.WebControls.TreeView.Nodes.get'
Source Error:
Line 43: {
Line 44: TreeView.Nodes.Add(directoryNode);
Line 45: }
Line 46: else
雖然Treeview是在asp.Net窗體中聲明的。我不知道這裏有什麼問題。任何幫助是極大的讚賞。由於
您需要創建一個根節點並開始向其添加節點。 44行沒有任何意義。 – Vlad
第44行應將根節點添加到TreeView。然後出現子節點的else語句。 –
您的代碼中的TreeView是類的名稱,而不是您的TreeView實例的名稱。不好的選擇來命名你的treeview控件。叫它MyTreeView什麼的。 – Vlad