2012-02-20 73 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

回答