Search code examples
c#toolstripmenu

ToolStripMenuItem items show in the incorrect location


I have a ToolStripMenuItem that contain submenus to select from. The problem is that they are displaying in the wrong place:enter image description here

I have this code that I used for the submenu (this was for the ToolStripCombobox -Thank you Reza for the solution-) of the above items but I'm having a hard time tweaking in to make it work for the ToolStripMenuItem as it does not contain a Control.Parent.GetType() :

private void Form_Load(object sender, EventArgs e)
    {
        var item = toolStripComboBox;
        var createControl = item.Control.Parent.GetType().GetMethod("CreateControl",
            System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
        createControl.Invoke(item.Control.Parent, new object[] { true });

As always, any help is appreciated.


Solution

  • I think the root of your whole problem is your using the form load event handler instead of the form constructor. When I run the following code, the menu items are in exactly the right place when the form loads:

    public Form1()
    {
        InitializeComponent();
        ToolStripComboBox item1 = new ToolStripComboBox();
        item1.Items.AddRange(new object[]
        {
            "One",
            "Two",
            "Thtree"
        });
        item1.DropDownStyle = ComboBoxStyle.Simple;
        menuStrip1.Items.Add(item1);
        ToolStripMenuItem item2 = new ToolStripMenuItem();
        item2.Text = "Four";
        menuStrip1.Items.Add(item2);
    }