c# 遞迴樹形選單
阿新 • • 發佈:2020-05-12
首先建立模型類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); //遞迴呼叫自己,直到父節點新增所有子節點結束 } }
效果展示