Treeview - 树状模型
利用递归添加数据
数据放入 treeView1.Nodes.Add() 中
public Form3() { InitializeComponent(); TreeNode t1 = new TreeNode("中国"); TreeNode t2 = new TreeNode("北京"); TreeNode t3 = new TreeNode("朝阳区"); t2.Nodes.Add(t3); t1.Nodes.Add(t2); treeView1.Nodes.Add(t1); }
问题是,地区代号在哪里了?——tag 与对象关联的用户定义数据
==================================================
public partial class Form3 : Form { List<China> alllist = new List<China>(); public Form3() { InitializeComponent(); alllist = new ChinaData().Select(); TreeNode tn1 = new TreeNode("中国"); tn1.Tag = "0001"; NodesBind(tn1); treeView1.Nodes.Add(tn1); } public void NodesBind(TreeNode tn) { 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); } } }