主页面
数据库(基于之前的省市数据库)
主程序
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace treeview1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } // 首先将所有数据读取出来,在进行递归排列 List<Info> list = new List<Info>(); private void Form1_Load(object sender, EventArgs e) { InitData(); AddTree(0, null); } void InitData() { SqlConnection conn = new SqlConnection("server=PC201609230944\SQL2005;database=HeiMaBlog;user=sa;pwd=123456"); SqlCommand cmd = new SqlCommand("select * from Area", conn); conn.Open(); SqlDataReader dr = cmd.ExecuteReader(); if (dr.HasRows) { while (dr.Read()) { Info nin = new Info() { Ar_id = dr.GetInt32(0), Ar_name = dr[1].ToString(), Ar_uid = dr.GetInt32(2) }; list.Add(nin); } } } // 递归 // 父id和父节点 // 省:父id = 0,父节点是trMain void AddTree(int pid, TreeNode pnod) { foreach (Info item in list) { if (item.Ar_uid == pid) { // 新建一个节点,并且给节点赋值 TreeNode tnod = new TreeNode(); tnod.Text = item.Ar_name; if (pnod == null) { // 父节点为null,添加到trMain trMain.Nodes.Add(tnod); } else { //不是,就添加到父级点上 pnod.Nodes.Add(tnod); } AddTree(item.Ar_id, tnod); } } } } }
辅助
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace treeview1 { class Info { /// <summary> /// 地区编号 /// </summary> int ar_id; public int Ar_id { get { return ar_id; } set { ar_id = value; } } /// <summary> /// 地区名字 /// </summary> string ar_name; public string Ar_name { get { return ar_name; } set { ar_name = value; } } /// <summary> /// 地区父级 /// </summary> int ar_uid; public int Ar_uid { get { return ar_uid; } set { ar_uid = value; } } } }