treeview递归加载

实体类:

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[].ToString();
c.AreaName = dr[].ToString();
c.ParentAreaCode = dr[].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[].ToString();
c.AreaName = dr[].ToString();
c.ParentAreaCode = dr[].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 = ""; 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);
}
} }
}

treeview递归加载

上一篇:Building,Packaging,Deploying,and Administering Applications and Types


下一篇:Topshelf一个用于使用.NET构建Windows服务框架