转载:http://www.cnblogs.com/igoogleyou/archive/2012/12/17/treeview2.html
一,通过查询数据库的方法
ID 为主键,PID 表明数据之间的关系。
/// <summary> /// 生产树的代码; /// </summary> /// <param name="node"> 根节点</param> /// <param name="id">主键</param> private void CreateTwo(TreeNode node, int id) { string strSql = "select * from TableTest where PID = " + id; DataTable dt = SqlClass.GetTable(strSql); if (id == 0) // id = 0 是根节点 { for (int i = 0; i < dt.Rows.Count; i++) { TreeNode nd = new TreeNode(); nd.Text = dt.Rows[i]["Name"].ToString(); CreateTwo(nd, Convert.ToInt32(dt.Rows[i]["id"].ToString())); tvwTwo.Nodes.Add(nd); } } else { for (int i = 0; i < dt.Rows.Count; i++) { TreeNode Tnode = new TreeNode(); Tnode.Text = dt.Rows[i]["Name"].ToString(); CreateTwo(Tnode, Convert.ToInt32(dt.Rows[i]["id"].ToString())); node.Nodes.Add(Tnode); } } }
则个代码比较简单 只需要查询一个数据表。
不过会查询多次,我觉得不合适。
所以第二个方法,全部拿出来,在缓存里操作。
生成结果:
-------------------------------------------------------------------------------------------------------------------------------
二,通过linq 获取菜单的通用方法:
static void Main(string[] args) { //最终结果 UserR ur = new UserR(); //调用 Create(ur, 0); //打印 Print(ur); string str = JsonConvert.SerializeObject(ur); Console.ReadLine(); } //测试数据 static List<User> list = new List<User>() { new User(){id=1,name="food",parentId=0}, new User(){id=2,name="fruit",parentId=1}, new User(){id=3,name="red",parentId=2}, new User(){id=4,name="cherry",parentId=3}, new User(){id=5,name="yellow",parentId=2}, new User(){id=6,name="banana",parentId=5}, new User(){id=7,name="meat",parentId=1}, new User(){id=8,name="beef",parentId=7}, new User(){id=9,name="pork",parentId=7}, }; //递归遍历 private static void Create(UserR node, int id) { var q = list.Where(x => x.parentId == id).ToList(); for (int i = 0; i < q.Count; i++) { UserR nd = new UserR(); nd.id = q[i].id; nd.name = q[i].name; Create(nd, q[i].id); node.u.Add(nd); } } //打印查看结果 static void Print(UserR ur) { Console.WriteLine(ur.name); if (ur.u != null) foreach (var item in ur.u) { Print(item); } } //查询出的实体层 public class User { public int id { get; set; } public string name { get; set; } public int parentId { get; set; } } //遍历后的实体层 public class UserR { public int id { get; set; } public string name { get; set; } public List<UserR> u = new List<UserR>(); public int parentId { get; set; } }