无限极分类绑定TreeView控件效果

今天搞了一个早上,就是无限极分类绑定TreeView 控件显示效果。结果一个递归算法把我搞死了,还是互联网强大,在此感谢cctv,mtv,musicmv。

下面这是我的数据库的建表代码

create table tree
(
 treeId int identity(1,1) primary key,----主键递增
 treeName varchar(50) not null,----分类名称
 treeNo int default 0---父类ID为0表示第一大类
)

下面是我数据库里的数据

treeId      treeName                                           treeNo     
----------- -------------------------------------------------- -----------
1           第一大类                                               0
2           2级分类                                               1
3           3级分类                                               2
4           4级分类                                               3
5           第二大类                                               0
6           2级分类                                               5
7           3级分类                                               6
8           第三大类                                               0
9           第四大类                                               0
10          5级分类                                               4
11          2级分类                                               8
12          3级分类                                               11
13          2级分类                                               9
14          3级分类                                               13

 

asp.net 代码

/// <summary> /// 控件绑定 /// </summary> private void TreeViewBind() { string sql = "select * from tree"; DataSet ds = SqlHelper.dataSet(SqlHelper.connectionString, CommandType.Text, sql);//此处调用了获的dt的代码,不加入了,自己写. DataView dv = ds.Tables[0].DefaultView; dv.RowFilter = "treeNo=0"; TreeView1.ShowCheckBoxes = TreeNodeTypes.All; foreach (DataRowView drv in dv) { TreeNode node = new TreeNode(); node.Text = drv["treeName"].ToString(); node.Value = drv["treeId"].ToString(); node.Expanded = false; TreeView1.Nodes.Add(node); AddReplies(dv, node); } } /// <summary> /// 递归绑定子节点 /// </summary> /// <param name="dv"></param> /// <param name="node"></param> private void AddReplies(DataView dv, TreeNode node) { dv.RowFilter = "treeNo='"+node.Value+"'"; foreach (DataRowView row in dv) { TreeNode replyNode = new TreeNode(); replyNode.Text = row["treeName"].ToString(); replyNode.Value = row["treeId"].ToString(); replyNode.Expanded = false; node.ChildNodes.Add(replyNode); AddReplies(dv, replyNode); } }

效果如下

 

图片

你可能感兴趣的:(sql,数据库,String,tree,asp.net,dataset)