.net 无限分类

1、建立数据库

image

image

image

2、建立一个新页面Default2.aspx,里面拖一个TreeView就好了;

3、修改页面后台代码:Default2.aspx.cx;

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;
using System.Data.SqlClient;

public partial class Default2 : System.Web.UI.Page
{
IList list = new List();

protected void Page_Load(object sender, EventArgs e)
{
//首次加载
if (!this.IsPostBack)
{
SqlConnection con = new SqlConnection("server=.;uid=sa;pwd=sa;database=coll");
SqlCommand cmd = new SqlCommand("select * from category", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
//得到数据库中的所有记录, 并存放到集合之中
while (reader.Read())
{
Category c = new Category();
c.CategoryID = reader.GetInt32(0);
c.ParentID = reader.GetInt32(1);
c.Layer = reader.GetInt32(2);
c.Name = reader.GetString(3);
list.Add(c);
}
reader.Close();
cmd.Dispose();
con.Close();

//执行添加树节点的方法
this.AddTreeNode(0, null);
}
}
///
/// 添加树节点的方法
///
///

父节点
/// 节点
private void AddTreeNode(int parentId, TreeNode node)
{
List categorylist = new List();
//遍历原集合,找到父节点是parentId的对象,加到新的集合
//(里面就全部是父节点为parentId的对象了)
foreach (Category c in this.list)
{
if (c.ParentID == parentId)
categorylist.Add(c);
}
//如果父节点为了parentId的元素的个数不为0
if (categorylist.Count > 0)
{
//遍历集合
foreach (Category cate in categorylist)
{
//构建新节点
TreeNode tNode = new TreeNode();
tNode.Text = cate.Name;
//如果传入的节点为空,则证明此节点为根节点,添加即可
if (node == null)
{
this.TreeView1.Nodes.Add(tNode);
}
//否则,此节点为一般节点,在传入的节点的子节点下加入此节点即可
else
{
node.ChildNodes.Add(tNode);
}
this.AddTreeNode(cate.CategoryID, tNode);
}
}
}
}

你可能感兴趣的:(.net)