Combo box in a scrollable panel causing problems

Posted by Dennis on Stack Overflow See other posts from Stack Overflow or by Dennis
Published on 2010-11-08T21:19:45Z Indexed on 2011/01/01 5:54 UTC
Read the original article Hit count: 329

I have a panel with AutoScroll set to true. In it, I am programmatically adding ComboBox controls. If I add enough controls to exceed the viewable size of the panel a scroll bar appears (so far so good). However, if I open one of the combo boxes near the bottom of the viewable area the combo list isn't properly displayed and the scrollable area seems to be expanded. This results in all of the controls being "pulled" to the new bottom of the panel with some new blank space at the top. If I continue to tap on the drop down at the bottom of the panel the scrollable area will continue to expand indefinitely. I'm anchoring the controls to the left, right and top so I don't think anchoring is involved. Is there something obvious that could be causing this?

Update: It looks like the problem lies with anchoring the controls to the right. If I don't anchor to the right then I don't get the strange behavior. However, without right anchoring the control gets cut off by the scroll bar.

Here's a simplified test case I built that shows the issue:

    public Form1()
    {
        InitializeComponent();

        Panel panel = new Panel();
        panel.Size = new Size(80, 200);
        panel.AutoScroll = true;

        for (int i = 0; i < 10; ++i)
        {
            ComboBox cb = new ComboBox();
            cb.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
            cb.Items.Add("Option 1");
            cb.Items.Add("Option 2");
            cb.Items.Add("Option 3");
            cb.Items.Add("Option 4");
            cb.Location = new Point(0, i * 24);
            panel.Controls.Add(cb);
        }

        Controls.Add(panel);
    }

If you scroll the bottom of the panel and tap on the combo boxes near the bottom you'll notice the strange behavior.

© Stack Overflow or respective owner

Related posts about c#

Related posts about winforms