最近需要做无限级分类,在网上看了好多例子都不怎么具体,因此小结一下,写个详细点的例子.第一次发文章,希望大家不要见笑.
1.数据库设计
create table TreeTemp
(
ChildMenuID int identity,
ParentMenu int,
MenuName varchar(50),
)
本例的数据: ChildMenuID ParentMenu MenuName
1 | 0 | 0 | 2 | 1 | 01 | 3 | 1 | 02 | 4 | 1 | 03 | 5 | 3 | 0201 | 6 | 2 | 0102 | 7 | 9 | 010101 | 8 | 4 | 0301 | 9 | 2 | 0101 | 10 | 4 | 0302 | 11 | 6 | 010201 | 2.代码部分,新建一个TreeView类,写入如下代码:
- using System;
- using System.Data;
- using System.Configuration;
- 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.Data.SqlClient;
- public class TreeClass
- {
- public TreeClass()
- {
-
-
-
- }
-
-
-
-
-
-
- public static bool buildTree(System.Web.UI.WebControls.TreeView TreeViewName, DataSet ds)
- {
- TreeViewName.Nodes.Clear();
- ds.Relations.Add("NodeRelation", ds.Tables[0].Columns["ChildMenuID"], ds.Tables[0].Columns["ParentMenu"],false);
-
- foreach (DataRow dbrow in ds.Tables[0].Rows)
- {
- if(Convert.ToString(dbrow["ParentMenu"])=="0")
- {
- TreeNode newNode = CreateNode(dbrow["MenuName"].ToString());
- TreeViewName.Nodes.Add(newNode);
- ChildTree(dbrow, newNode);
- }
- }
- return true;
- }
-
-
-
-
-
- private static void ChildTree(DataRow dbrow, System.Web.UI.WebControls.TreeNode node)
- {
- foreach (DataRow childRow in dbrow.GetChildRows("NodeRelation"))
- {
- TreeNode childNode = CreateNode(childRow["MenuName"].ToString());
- node.ChildNodes.Add(childNode);
- ChildTree(childRow, childNode);
- }
- }
-
-
-
-
-
-
- private static System.Web.UI.WebControls.TreeNode CreateNode(string text)
- {
- TreeNode node = new TreeNode();
- node.Text = text;
- return node;
- }
- }
在页面中调用此类即可实现功能. | | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |