asp.net Treeview

CREATE TABLE test
(
    Id INT IDENTITY(1,1)PRIMARY KEY,
    NAME VARCHAR(20),
    ParentId INT 
)

INSERT test VALUES('首页',0)
INSERT test VALUES('新闻',1)
INSERT test VALUES('国内新闻',2)
INSERT test VALUES('国外新闻',2)
INSERT test VALUES('社会',3)
INSERT test VALUES('军事',3)
INSERT test VALUES('娱乐',3)
INSERT test VALUES('香港新闻',2)
INSERT test VALUES('澳门新闻',2)
INSERT test VALUES('产品',1)
INSERT test VALUES('简介',1)
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                TreeNode nodeCategory;

                List<Category> category = getList();
                Stack<Category> storeCategory = new Stack<Category>();
                storeCategory.Push(category[0]);
                nodeCategory = new TreeNode(category[0].Name.Trim(), category[0].Id.Trim());
                TreeView1.Nodes.Add(nodeCategory);
                getTreeView(storeCategory, category, nodeCategory);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public List<Category> getList()
        {
            SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=master;Integrated Security=true;");
            conn.Open();
            SqlCommand cmd = new SqlCommand("select * from test", conn);
            SqlDataReader reader = cmd.ExecuteReader();
            List<Category> lc = new List<Category>();
            while (reader.Read())
            {
                Category cate = new Category();
                cate.Id = reader["Id"].ToString();
                cate.Name = reader["Name"].ToString();
                cate.Parentid = reader["parentid"].ToString();
                lc.Add(cate);
            }
            return lc;
        }
        public void getTreeView(Stack<Category> categoryStack, List<Category> categoryList, TreeNode e)
        {
            Category tmp;
            if (categoryStack.Count > 0)
            {
                tmp = categoryStack.Pop();
                for (int i = 0; i < categoryList.Count; i++)
                    if (categoryList[i].Parentid.Trim() == tmp.Id.Trim())
                    {
                        categoryStack.Push(categoryList[i]);
                        TreeNode childNote = new TreeNode(categoryList[i].Name.Trim(), categoryList[i].Id.Trim());
                        e.ChildNodes.Add(childNote);
                        getTreeView(categoryStack, categoryList, childNote);
                    }
            }
        } 

posted @ 2012-07-06 10:10  望月狼  阅读(217)  评论(0编辑  收藏  举报