在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
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); } } } |
请发表评论