2016-06-08 50 views
0

我試圖從我的根目錄中的一個文件夾(稱爲文件夾)構建文件和文件夾的樹視圖。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窗體中聲明的。我不知道這裏有什麼問題。任何幫助是極大的讚賞。由於

+0

您需要創建一個根節點並開始向其添加節點。 44行沒有任何意義。 – Vlad

+0

第44行應將根節點添加到TreeView。然後出現子節點的else語句。 –

+0

您的代碼中的TreeView是類的名稱,而不是您的TreeView實例的名稱。不好的選擇來命名你的treeview控件。叫它MyTreeView什麼的。 – Vlad

回答

0
Server.MapPath("~/Folders/") 

將尋找一個文件夾,名爲文件夾ASP.NET項目內:

Folders folder inside the web application project

我所做的一切就是確保我有我的項目在此文件夾與一對夫婦的子文件夾,它的工作很好:

輸出在瀏覽器中:

ASP.NET TreeView control