I believe it's because MenuItem can only belong to one single parent MenuItem (though I'm not 100% positive - MSDN doesn't mention anything about that in
http://msdn.microsoft.com/en-us//library/system.windows.forms.menuitem%28v=vs.110%29.aspx[
^], so it requires disassembling to be sure). But since it has
Parent
property, which refers to the parent menu item, I think it's true. If menu item can only have single parent, it means every time you add this menu item to another menu, the said item is "detached" from the parent it previously belonged to.
So, to fix your issue, I'd propose one of the following:
1) Put
MenuItem[] subChild = new MenuItem[3];
subChild[0] = new MenuItem("Digital", IO_Click);
subChild[1] = new MenuItem("Analog", IO_Click);
subChild[2] = new MenuItem("Special", IO_Click);
block in both of the cycles for
opChild
and
inChild
:
2) Use
CloneMenu()
method which creates a duplicate of the current object, e.g.
ipChild[ip].MenuItems.Add(subChild[0].CloneMenu());
UPD: I discovered that MSDN actually mentions this restrinction in
CloneMenu()
method description:
MenuItem objects cannot be used in more than one place unless you obtain a copy of the MenuItem. Also, since
CloneMenu()
performs a deep copying (i.e. also creates a copy of all the submenus), I propose the following code with less arrays:
case System.Windows.Forms.MouseButtons.Right:
case System.Windows.Forms.MouseButtons.Right:
MenuItem pTypeSubmenu = new MenuItem(string.Empty, IO_Click);
pTypeSubmenu.MenuItems.Add(new MenuItem("Digital", IO_Click));
pTypeSubmenu.MenuItems.Add(new MenuItem("Analog", IO_Click));
pTypeSubmenu.MenuItems.Add(new MenuItem("Special", IO_Click));
MenuItem[] parent = new MenuItem[2];
parent[0] = new MenuItem("InPut", IO_Click);
parent[1] = new MenuItem("OutPut", IO_Click);
MenuItem pSubmenu = null;
for (int ip = 0; ip < 9; ip++)
{
pSubmenu = pTypeSubmenu.CloneMenu();
pSubmenu.Text = "Input " + (ip + 1).ToString();
parent[0].MenuItems.Add(pSubmenu);
}
for (int op = 0; op < 6; op++)
{
pSubmenu = pTypeSubmenu.CloneMenu();
pSubmenu.Text = "Output " + (op + 1).ToString();
parent[1].MenuItems.Add(pSubmenu);
}
lstViewMenu = new ContextMenu(parent);
lstViewMenu.Show(lstView, e.Location);
break;
default:
break;