递归树

来源:互联网 发布:微信支付java服务器端 编辑:程序博客网 时间:2024/05/15 19:03
  1. using System;
  2. using System.Data;
  3. using System.Configuration;
  4. using System.Collections;
  5. using System.Web;
  6. using System.Web.Security;
  7. using System.Web.UI;
  8. using System.Web.UI.WebControls;
  9. using System.Web.UI.WebControls.WebParts;
  10. using System.Web.UI.HtmlControls;
  11. using System.Collections.Generic;
  12. using System.Data.SqlClient;
  13. public partial class Default2 : System.Web.UI.Page
  14. {
  15.     IList<Category> list = new List<Category>();
  16.     protected void Page_Load(object sender, EventArgs e)
  17.     {
  18.         if (!this.IsPostBack)
  19.         {
  20.             SqlConnection con = new SqlConnection("server=.;uid=sa;pwd=;database=coll");
  21.             SqlCommand cmd = new SqlCommand("select * from category", con);
  22.             con.Open();
  23.             SqlDataReader reader = cmd.ExecuteReader();
  24.             while (reader.Read())
  25.             {
  26.                 Category c = new Category();
  27.                 c.CategoryID = reader.GetInt32(0);
  28.                 c.ParentID = reader.GetInt32(1);
  29.                 c.Layer = reader.GetInt32(2);
  30.                 c.Name = reader.GetString(3);
  31.                 list.Add(c);
  32.             }
  33.             reader.Close();
  34.             cmd.Dispose();
  35.             con.Close();
  36.             this.AddTreeNode(0, null);
  37.         }
  38.     }
  39.     private void AddTreeNode(int parentId, TreeNode node)
  40.     {
  41.         List<Category> categorylist = new List<Category>();
  42.         foreach (Category c in this.list)
  43.         {
  44.             if (c.ParentID == parentId)
  45.                 categorylist.Add(c);
  46.         }
  47.         if (categorylist.Count > 0)
  48.         {
  49.             foreach (Category cate in categorylist)
  50.             {
  51.                 TreeNode tNode = new TreeNode();
  52.                 tNode.Text = cate.Name;
  53.                 if (node == null)
  54.                 {
  55.                     this.TreeView1.Nodes.Add(tNode);
  56.                 }
  57.                 else
  58.                 {
  59.                     node.ChildNodes.Add(tNode);
  60.                 }
  61.                 this.AddTreeNode(cate.CategoryID, tNode);
  62.             }
  63.         }
  64.     }
  65. }
原创粉丝点击