实体类:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WindowsFormsApplication2 { public class China { public string AreaCode { get; set; } public string AreaName { get; set; } public string ParentAreaCode { get; set; } } }
数据访问类:
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; namespace WindowsFormsApplication2 { public class ChinaData { SqlConnection conn = null; SqlCommand cmd = null; public ChinaData() { conn = new SqlConnection("server=.;database=mydb;user=sa;pwd=123"); cmd = conn.CreateCommand(); } public List<China> Select(string pcode) { List<China> clist = new List<China>(); cmd.CommandText = "select *from ChinaStates where ParentAreaCode = '" + pcode + "'"; conn.Open(); SqlDataReader dr = cmd.ExecuteReader(); if (dr.HasRows) { while (dr.Read()) { China c = new China(); c.AreaCode = dr[0].ToString(); c.AreaName = dr[1].ToString(); c.ParentAreaCode = dr[2].ToString(); clist.Add(c); } } conn.Close(); return clist; } public List<China> Select() { List<China> clist = new List<China>(); cmd.CommandText = "select *from ChinaStates"; conn.Open(); SqlDataReader dr = cmd.ExecuteReader(); if (dr.HasRows) { while (dr.Read()) { China c = new China(); c.AreaCode = dr[0].ToString(); c.AreaName = dr[1].ToString(); c.ParentAreaCode = dr[2].ToString(); clist.Add(c); } } conn.Close(); return clist; } } }
form1:treeview 使用递归
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication2 { public partial class Form1 : Form { List<China> AllList = new List<China>(); public Form1() { InitializeComponent(); AllList = new ChinaData().Select(); TreeNode tn1 = new TreeNode("中国"); tn1.Tag = "0001"; NodesBind(tn1); treeView1.Nodes.Add(tn1); } public void NodesBind(TreeNode tn) { //lambda 表达式 List<China> clist = AllList.Where(r => r.ParentAreaCode == tn.Tag.ToString()).ToList(); foreach (China c in clist) { TreeNode tnn = new TreeNode(c.AreaName); tnn.Tag = c.AreaCode; NodesBind(tnn); tn.Nodes.Add(tnn); } } } }