2012-02-20 38 views
-2

我有問題試圖使用asp.net和c#構建樹視圖。創建樹視圖c#asp.net - 展開所有節點

我的結果是試圖證明這樣一個TreeView(對不起,錯拼寫或錯誤的位置,但是這僅僅是測試數據):

UK 
    -> London 
    -> SouthEast 
     ->Kent 
     ->Essex 
    -> NorthEast 
     ->Cambridge 
Wales 
    -> Cardiff 

這裏是我下面的代碼:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" 
    ValidateRequest="false" %> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <asp:TreeView ID="TreeView1" runat="server" > 
       </asp:TreeView> 
    </form> 
</body> 
</html> 

C#:

using System; 
using System.Collections.Generic; 
using System.Web.UI.WebControls; 
using System.Collections.ObjectModel; 

namespace WebApplication1 
{ 
    public partial class WebForm1 : System.Web.UI.Page 
    { 
     public class ViewModel 
     {   
      public string LocationName { get; set; }   
     } 
     protected void Page_Load(object sender, EventArgs e) 
     { 
      ICollection<ViewModel> list = new Collection<ViewModel>(); 
      list.Add(new ViewModel { LocationName = "UK" }); 
      list.Add(new ViewModel { LocationName = "UK.London.SouthEast.Kent" }); 
      list.Add(new ViewModel { LocationName = "UK.London.SouthEast.Essex" }); 
      list.Add(new ViewModel { LocationName = "Wales.Cardiff" }); 
      list.Add(new ViewModel { LocationName = "Wales" }); 
      list.Add(new ViewModel { LocationName = "UK.London.NorthEast.Cambridge" }); 

      PopulateTreeview(list); 
     } 

     private void PopulateTreeview(ICollection<ViewModel> listOfCities) 
     { 
      foreach (ViewModel vm in listOfCities) 
      { 
        TreeNode tnNode = new TreeNode(); 
        tnNode.Text = vm.LocationName; 
        tnNode.Value = vm.LocationName;      
        tnNode.Expanded = true;     
        TreeView1.Nodes.Add(tnNode);     
      } 
     } 
    } 
} 

正如你可以看到我的測試數據是這樣的格式 「UK.London.SouthEast.Essex」。我將從DB獲取這些數據。我需要使用這些數據構建一個父節點和子節點,但不知道如何去做?一直試圖寫幾天如何做到這一點。

+0

你做了一個谷歌搜索..有很多的例子..這裏是一個StackOverFlow同樣的問題的例子你明白LINQ或lambda的?? ?? http://stackoverflow.com/questions/447639/how-to-build-an-asp-net-treeview-from-scratch – MethodMan 2012-02-20 13:47:16

+3

這是因爲你所做的一切都是錯誤的;你將所有的孩子都添加到根節點,甚至沒有在層次結構中尋找*,那麼你如何期望它能夠工作? – Shai 2012-02-20 13:47:29

回答