Strange empty spaces in FlowLayoutPanel
Asked Answered
P

1

8

I have lots of buttons on flowlayoutpanel, and then there's text labels to break the flow. Last button before label and label itself has SetFlowBreak. All works kind of fine, but what I don't understand, is why there is so much space under the text label? If form is resized so narrow that there's only one column of buttons, then the unwanted space disappears. Can someone explain how that space can be removed?

Code:

public Form1()
{
    InitializeComponent();

    for (int i = 1; i <= 100; i++)
    {
        Button button = new Button();
        button.Text = i.ToString();
        button.Width = 150;
        button.Height = 50;
        button.Margin = new Padding(5);
        flowLayoutPanel1.Controls.Add(button);

        if (i % 10 == 0)
        {
            flowLayoutPanel1.SetFlowBreak(button, true);

            Label label = new Label();
            label.Text = "Some random text";
            label.AutoSize = true;
            label.Margin = new Padding(5, 5, 0, 0);
            label.BackColor = ColorTranslator.FromHtml("#ccc");
            flowLayoutPanel1.Controls.Add(label);

            flowLayoutPanel1.SetFlowBreak(label, true);

        }
    }
}

And couple of images to show what I mean:

Image1: Strange space under the Label enter image description here

Image2: No space under the Label when the form is resized (this is how I'd like this to work) enter image description here

Prevailing answered 3/5, 2014 at 18:18 Comment(4)
Actually the space below the label disappears only when you get really close; I can see it before, even though there is onyl one column of buttons..Antrorse
You are right. I didn't notice that before.Prevailing
Not that that helps - looks like a bug..Antrorse
It is a bug, same one as this one. The extra space is the height of the next label. The workaround is exactly the same, just add a dummy control with a Width of 0 after the label.Technics
P
7

Thank you Hans! I thinks this is a real answer, as it solved my problem: (quote from comments)

It is a bug, same one as this one. The extra space is the height of the next label. The workaround is exactly the same, just add a dummy control with a Width of 0 after the label. – Hans Passant

So first I removed flowbreak after the real label:

flowLayoutPanel1.SetFlowBreak(label, true);

And then replaced it with the following code, and the mysterious space disappeared!

Label dummyLabel = new Label();
dummyLabel.Width = 0;
dummyLabel.Height = 0;
dummyLabel.Margin = new Padding(0, 0, 0, 0);

flowLayoutPanel1.Controls.Add(dummyLabel);
flowLayoutPanel1.SetFlowBreak(dummyLabel, true);

Fixed

Prevailing answered 4/5, 2014 at 9:16 Comment(2)
Welcome to SO. +1 for posting the answer to your question. I would recommend accepting it as well...Rice
Thanks. I will, but SO would'n let me accept it until tomorrow.Prevailing

© 2022 - 2024 — McMap. All rights reserved.