动态生成ContextMenuStrip

数据表:

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication25
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 窗体加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            ToolStripMenuItem tmpItem = new ToolStripMenuItem("移动到");
            this.contextMenuStrip1.Items.Add(tmpItem);

            CreateContextMenuStrip(tmpItem.DropDownItems, GetTable(), 1);
        }

         /// <summary>
         /// ContextMenuStrip中DropDownItem单击事件
      /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void MenuClicked(object sender, EventArgs e)
        {
            MessageBox.Show((sender as ToolStripMenuItem).Text);
        }

        /// <summary>
        /// 递归生成ContextMenuStrip
        /// </summary>
        /// <param name="items"></param>
        /// <param name="dt"></param>
        /// <param name="parentId"></param>
        public void CreateContextMenuStrip(ToolStripItemCollection items, DataTable dt, int parentId)
        {
            if (dt.Rows.Count == 0)
                return;
            string fliter = string.Format("ParentGroup={0}", parentId);
            DataRow[] dr = dt.Select(fliter);
            foreach (DataRow row in dr)
            {
                ToolStripMenuItem menuitem;
                menuitem = new ToolStripMenuItem();
                menuitem.Text = row["GroupName"].ToString();
                menuitem.Name = row["ID"].ToString();
                menuitem.Click += new EventHandler(MenuClicked);
                items.Add(menuitem);
                CreateContextMenuStrip(menuitem.DropDownItems, dt, Convert.ToInt32(row["ID"]));
                dt.Rows.Remove(row);
            }
        }

        /// <summary>
        /// 获取数据源
        /// </summary>
        /// <returns></returns>
        DataTable GetTable()
        {
            SqlDataAdapter da = new SqlDataAdapter("select * from ReportGroup", "server=(local);uid=sa;pwd=123;database=ExcelMaster;");
            DataTable dt = new DataTable();
            da.Fill(dt);
            return dt;
        }

    }
}

结果:

原文地址:https://www.cnblogs.com/lisengl/p/2587425.html