- 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<Category> list = new List<Category>();
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!this.IsPostBack)
- {
- SqlConnection con = new SqlConnection("server=.;uid=sa;pwd=;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<Category> categorylist = new List<Category>();
- foreach (Category c in this.list)
- {
- if (c.ParentID == parentId)
- categorylist.Add(c);
- }
- 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);
- }
- }
- }
- }
递归树
最新推荐文章于 2023-06-15 10:27:20 发布