Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do get items to merge into the middle of a menu, in the right order AND

There are several factors that contribute to the being a bit tricky. One is the fact that MergeIndex is ignored when MergeAction = Append. The second is the live nature of the merge; incoming items affect the index. To accomplish this, order the items in the source merge list in reverse, select them all and set MergeAction to Insert and MergeIndex to the index of where in the target you want them inserted. The example below shows a runtime version of this. The result is an alphabetically ordered dropdown.

// target menustrip
MenuStrip veggieMenuStrip = new MenuStrip();
ToolStripMenuItem veggieMenuStripItem = veggieMenuStrip.Items.Add("Veggies") as ToolStripMenuItem;
veggieMenuStripItem.DropDownItems.Add("Asparagus");
veggieMenuStripItem.DropDownItems.Add("Jicama");
veggieMenuStripItem.DropDownItems.Add("Kale");

// source menustrip
MenuStrip veggieMenuStrip2 = new MenuStrip();
ToolStripMenuItem veggieMenuStripItem2 = veggieMenuStrip2.Items.Add("Veggies") as ToolStripMenuItem;
veggieMenuStripItem2.DropDownItems.Add("Cauliflower");
veggieMenuStripItem2.DropDownItems.Add("Bok Choy");

// set top level item to MatchOnly
veggieMenuStripItem2.MergeAction = MergeAction.MatchOnly;

// set all child items to insert at 1 (zero based)
// insert between Asparagus and Jicama
foreach (ToolStripMenuItem tsmi in veggieMenuStripItem2.DropDownItems)
{
tsmi.MergeAction = MergeAction.Insert;
tsmi.MergeIndex = 1; 
}

// do this on activation or focus
ToolStripManager.Merge(veggieMenuStrip2, veggieMenuStrip);

this.Controls.Add(veggieMenuStrip);