鉴于很多朋友对树的无限级分类频繁的读取数据库问题,写了一个优化版的无限级分类
TreeView.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="treeview.aspx.cs" Inherits="treeview" %>
<!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">
<div>
<asp:TreeView ID="tvTest" runat="server">
</asp:TreeView>
</div>
</form>
</body>
</html>
TreeView.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
public partial class treeview : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Display();
}
private void Display()
{
List<Book> listBook = GetAllBook(); //得到所有的数据
foreach (Book book in listBook)
{
//取第一层的数据
if (book.pid == 0) //假定父ID等于0
{
TreeNode TNode = new TreeNode(book.name);
tvTest.Nodes.Add(TNode);
TNode.NavigateUrl = "test.aspx?id=" + book.id;
TNode.Target = book.id.ToString();
AddChild(TNode, listBook);
}
}
}
private void AddChild(TreeNode td, List<Book> listBook)
{
foreach (Book item in listBook)
{
if (item.pid == int.Parse(td.Target))
{
TreeNode tn = new TreeNode(item.name);
td.ChildNodes.Add(tn);
tn.Target = item.id.ToString();
tn.NavigateUrl = "test.aspx?id=" + item.id;
//递归调用
AddChild(tn, listBook);
}
}
}
List<Book> GetAllBook()
{
List<Book> list = new List<Book>();
//第一级
Book model = new Book();
model.id = 1;
model.pid = 0;
model.name = "a";
list.Add(model);
Book model1 = new Book();
model1.id = 2;
model1.pid = 0;
model1.name = "b";
list.Add(model1);
//第二级
Book model2 = new Book();
model2.id = 3;
model2.pid = 1;
model2.name = "aa";
list.Add(model2);
//第三级
Book model3 = new Book();
model3.id = 4;
model3.pid = 3;
model3.name = "aaa";
list.Add(model3);
return list;
}
}
public class Book
{
private int _id;
private int _pid;
private string _name;
public int id
{
set { _id = value; }
get { return _id; }
}
public int pid
{
set { _pid = value; }
get { return _pid; }
}
public string name
{
set { _name = value; }
get { return _name; }
}
}