一个动态添加contextmenu的例子,以及其click事件
代码
1 private void frmMain_Load(object sender, EventArgs e)
2 {
3 List<string> list = new List<string>();
4 list.Add("SubItem1");
5 list.Add("SubItem2");
6 list.Add("SubItem3");
7
8 ContextMenu cm = new ContextMenu();
9 this.ContextMenu = cm;
10
11 MenuItem myItem = new MenuItem();
12 myItem.Text = "test";
13 foreach (string item in list)
14 {
15 MenuItem mi = new MenuItem(item);
16 mi.Name = item;
17 mi.Click += new EventHandler(CustomItem_Click); //这里为子菜单添加Click事件
18 myItem.MenuItems.Add(mi);
19 }
20 cm.MenuItems.Add(myItem);
21 }
22
23 private void CustomItem_Click(object sender, EventArgs e)
24 {
25 //根据sender的Name属性来区分是点了哪个了菜单,写相应的事件处理代码
26 MessageBox.Show(((MenuItem)sender).Name);
27 }
28
2 {
3 List<string> list = new List<string>();
4 list.Add("SubItem1");
5 list.Add("SubItem2");
6 list.Add("SubItem3");
7
8 ContextMenu cm = new ContextMenu();
9 this.ContextMenu = cm;
10
11 MenuItem myItem = new MenuItem();
12 myItem.Text = "test";
13 foreach (string item in list)
14 {
15 MenuItem mi = new MenuItem(item);
16 mi.Name = item;
17 mi.Click += new EventHandler(CustomItem_Click); //这里为子菜单添加Click事件
18 myItem.MenuItems.Add(mi);
19 }
20 cm.MenuItems.Add(myItem);
21 }
22
23 private void CustomItem_Click(object sender, EventArgs e)
24 {
25 //根据sender的Name属性来区分是点了哪个了菜单,写相应的事件处理代码
26 MessageBox.Show(((MenuItem)sender).Name);
27 }
28
用这种方式来动态添加菜单项 MenuItem menu1 = new MenuItem("新建班级&(C)"); menu1.Click += new EventHandler(menu1_Click); contextMenu1.MenuItems.Add(menu1); 然后你再写一个 private void menu1_Click(object sender, EventArgs e) { MessageBox.Show("新建班级 OnClick!"); } 就行了