首先创建模型类Menus
public class Menus { //菜单Id public int Id { get; set; } //菜单名 public string MenuName { get; set; } //父节点Id public int ParentId { get; set; } }
窗体中放入button跟TreeView控件
声明全局变量
private static List<Menus> menus;
添加按钮事件
private void button1_Click(object sender, EventArgs e) { menus = new List<Menus>(); menus.Add(new Menus { Id = 1, MenuName = "基础设置", ParentId = 0 }); menus.Add(new Menus { Id = 2, MenuName = "采购管理", ParentId = 0 }); menus.Add(new Menus { Id = 3, MenuName = "系统设置", ParentId = 1 }); menus.Add(new Menus { Id = 4, MenuName = "用户管理", ParentId = 1 }); menus.Add(new Menus { Id = 5, MenuName = "采购订单", ParentId = 2 }); menus.Add(new Menus { Id = 6, MenuName = "采购入库", ParentId = 2 }); menus.Add(new Menus { Id = 7, MenuName = "用户", ParentId = 4 }); menus.Add(new Menus { Id = 8, MenuName = "采购退货", ParentId = 2 }); menus.Add(new Menus { Id = 9, MenuName = "用户组", ParentId = 4 }); menus.Add(new Menus { Id = 10, MenuName = "权限管理", ParentId = 4 }); //首先查出顶级菜单,循环添加 IEnumerable<Menus> menu = from m in menus where m.ParentId == 0 orderby m.ParentId select m; foreach (var item in menu) { TreeNode node = new TreeNode(); node.Tag = item; node.Text = item.MenuName; treeView1.Nodes.Add(node); //将当前节点作为参数传入子节点 AddChildMenu(node); } }
子节点递归实现
private void AddChildMenu(TreeNode node) { Menus menu = new Menus(); menu = (Menus)node.Tag; //将父节点转为Model //查出当前子节点中所有同父节点Id一样的数据 IEnumerable<Menus> childMenu = from m in menus where m.ParentId == menu.Id orderby m.Id select m; foreach (var item in childMenu) { TreeNode childNode = new TreeNode(); childNode.Tag = item; childNode.Text = item.MenuName; node.Nodes.Add(childNode); //添加子节点 AddChildMenu(childNode); //递归调用自己,直到父节点添加所有子节点结束 } }
效果展示