现在的位置: 首页 > 综合 > 正文

使用递归结合TreeView完成树结构

2013年10月16日 ⁄ 综合 ⁄ 共 1853字 ⁄ 字号 评论关闭

前一篇博客中,本人介绍过递归的概念,可以大家不知道怎么用,下面结合一个实用的例子来加深大家的理解。

首先数据库中有这样一张表,数据如下:
cid  | cname | rid
----------------------
1    中国    0
2    北京市    1
3    广东省    1
4    上海市    1
5    广州市    3
6    深圳市    3
7    海珠区    5
8    天河区    5
9    福田区    6
10    南山区    6
11    密云县    2
12    浦东    4
最后我们希望能读取表中数据达到如下图1的显示效果:

treeViewresult_water3

首先我们做一些必要的准备工作。
DBHelper.cs类
内容如下:

class DBHelper
    {
        private static string url = "Data Source=.//sql2005express;Initial Catalog=master;User ID=sa;Password=123456";
        public static SqlConnection con =new SqlConnection(url);
    }

Country.cs实体类
public class Country
    {

        public Country()
        {
        }
        public Country(int cid,string cname,int rid)
        {
            this.cid = cid;
            this.cname = cname;
            this.Rid = rid;
        }
           private int cid; //自己id
        private string cname;
        private int rid; //父节点id
        //省略属性定义…
    }
----------------------

///通过id得到一个国家或地区实体的方法
public Country GetCountryById(int id){…}

///通过id得到该id的直接子节点链表的方法
public List GetCountryByParentId(int pid){…}
准备工作完毕后,定义如下的类:
//TreeViewDemo.cs的主要form类

public class TreeViewDemo{

//by 北大青鸟广州科苑讲师彭之军
TreeNode rnode = null;//根节点
       public TreeFormDemo()
       {
           InitializeComponent();

           rnode = RecursiveTree(1); //核心的递归方法
           treeViewArea.Nodes.Add(rnode);//将该根节点加入到treeView中
       }

   //递归求出节点
        public TreeNode RecursiveTree(int cid){…}

}

关键的代码在于这个RecursiveTree(int )这个方法。
代码详细如下:

//递归求出节点
       public TreeNode RecursiveTree(int cid)
       {
           //得到该id下的节点
           TreeNode node = new TreeNode(GetCountryById(cid).Cname);
           node.Tag = cid;
           //得到其下所有的子节点
           List list = this.GetCountryByParentId(cid);

           //遍历子节点链表
           foreach (Country c in list)
           {
               TreeNode n = new TreeNode(c.Cname);
               n.Tag = c.Cid;
               n = RecursiveTree(c.Cid); //递归
               node.Nodes.Add(n);
           }

           return node;
       }
读者可自行领会以上代码的注释。

 

Technorati 标签: ,,,

抱歉!评论已关闭.