Question

I have a menustrip that I create using the forms designer. I then want to programmatically add a toolstrip toolbar UNDER the menustrip. The reason is that this toolbar is a set of tools that I add as a plugin to the main application. As such, when the plugin is loaded, I create the toolbar.

When I manually add the toolstrip to the form using the forms designer, the toolstrip is correctly positioned under the menustrip. However when I add it programmatically, it snaps to the topmost part of the form, above the menustrip. Here's the code I use to programmatically add the toolstrip:

stereoBar = new ToolStrip();
stereoBar.Anchor = (AnchorStyles)(AnchorStyles.Top | AnchorStyles.Left);
//y location is set to 22, the width of the menustrip
stereoBar.Location = new System.Drawing.Point(0, 22);
stereoBar.Dock = DockStyle.Top;
stereoBar.Name = "StereoToolbar";
stereoBar.Text = "Stereo Plugin Toolbar";
stereoBar.ShowItemToolTips = true;
stereoBar.GripMargin = new Padding(2);
Controls.Add(stereoBar);

Is there anything simple I am missing here?

Thanks in advance!

Was it helpful?

Solution

As described also in this answer, when docking controls in a form the order in which you add them to the form matters; i.e. when adding multiple controls that all dock to the top, the last control that gets added will be the topmost.

So, because you add your toolstrip programmatically and your menu strip via designer, the designer code gets executed first thus having the menu strip always at the bottom.

I think there are three ways out of the dilemma:

First approach

As Hans Passant pointed out, the easiest way to get things into the right order would be to simply call

stereoBar.BringToFront();

right after you added it to the forms' controls.

Second approach

To circumvent this you could also also add the menu strip programmatically and do this after you added the tool strip.

Third approach

Another way out may be to add another container to the form (Panel or groupbox for example) via designer that also docks to the top that simply just functions as a placeholder where you add your tool strip to (so you do not add to the form directly anymore)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top