c# WinForm Menu自动生成

本文介绍了一种使用递归方式生成窗体菜单的方法,并详细展示了如何为菜单项添加事件响应。通过C#代码实现,从菜单数据源中筛选出当前层级的菜单项,创建 ToolStripMenuItem 对象并设置其显示文本和名称,再根据菜单项的链接函数添加点击事件。最后,递归调用自身以生成子菜单。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.将采用递归的方式生成窗体菜单,并且添加其事件响应

        Type t = typeof(frmMain);
        private void GenerateMenu(ToolStripItemCollection parentItem, List<SpinSystem.Domain.Main.Menu> menus,string paentId)
        {
            object o = this;

            if (menus == null) return;

            List<SpinSystem.Domain.Main.Menu> currentMenus = menus.Where(n => n.PARENT_ID == paentId).ToList();
            ToolStripMenuItem item = null;

            for (int i = 0; i < currentMenus.Count; i++)
            {
                if (!currentMenus[i].MENU_NAME.ToUpper().Equals("LINE"))
                {
                    item = new ToolStripMenuItem(currentMenus[i].MENU_DISPLAY);
                    item.Name = currentMenus[i].MENU_NAME;

                    MethodInfo info = t.GetMethod(currentMenus[i].LINK_FUNC);
                    if (info != null)
                    {
                        Delegate del = Delegate.CreateDelegate(typeof(EventHandler), o, info);
                        EventHandler myMethod = del as EventHandler;
                        item.Click += myMethod;
                    }

                    parentItem.Add(item);
                }
                else
                {
                    ToolStripSeparator line = new ToolStripSeparator();
                    parentItem.Add(line);
                    continue;
                }
                

                GenerateMenu(item.DropDownItems, menus, currentMenus[i].MENU_ID);
            }
        }

2.调用代码

 List<SpinSystem.Domain.Main.Menu> menus = services.GetMenuListByUserId(SpinSystem.Domain.Login.LoginUsercs.LoginUser.UserId);

 this.mnsMain.Items.Clear();
 GenerateMenu(this.mnsMain.Items,menus,"0");

 

转载于:https://www.cnblogs.com/YuanDong1314/p/9055088.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值