标签:
直接上代码吧,这里 MySql.Data.MySqlClient;需要到mysql官网下载mysql-connector-net-6.9.8-noinstall.zip 访问密码 6073
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using MySql.Data.MySqlClient; 7 using System.Data; 8 namespace ChinaRegionTreeView 9 { //连接数据库的类 10 class ConnectDB 11 { 12 private static String mysqlcon = "database=chinaregiondb;Password=1111;User ID=root;server=localhost"; 13 private MySqlConnection mysqlCon; 14 private DataSet ds; 15 MySqlDataAdapter mysqlAdapter = new MySqlDataAdapter(); 16 17 public DataSet Connect() 18 { 19 string sqlStr = "select * from chinaregiondb.tb_prov_city_area_street"; 20 mysqlAdapter = new MySqlDataAdapter(sqlStr, mysqlcon); 21 ds = new DataSet(); 22 mysqlAdapter.Fill(ds); 23 return ds; 24 } 25 } 26 }
1 public void TreeViewBind(DataTable dt,TreeNode parentNode,string parentID) 2 { 3 DataRow[] rows = dt.Select(string.Format("parentID={0}", parentID)); 4 foreach (DataRow row in rows) 5 { 6 TreeNode node=new TreeNode(){ 7 Text=row["name"].ToString() 8 }; 9 TreeViewBind(dt, node, row["code"].ToString()); 10 if (parentNode == null) 11 { 12 treeView1.Nodes.Add(node); 13 } 14 else 15 { 16 parentNode.Nodes.Add(node); 17 } 18 } 19 }
这个函数用的是递归,再用一个事件(button的click事件等)调用即可
1 private void button2_Click(object sender, EventArgs e) 2 { 3 treeView1.Nodes.Clear(); 4 ConnectDB conDB = new ConnectDB(); 5 dataGridView1.DataSource = conDB.Connect().Tables[0]; 6 TreeViewBind(conDB.Connect().Tables[0],null,"0"); 7 }
效果还不错吧,第一次写,吼吼
C# 使用winForm的TreeView显示中国城镇四级联动
标签:
原文地址:http://www.cnblogs.com/jnzdn/p/5256254.html