Bigsby
Bigsby

Reputation: 952

Programmatically added items to FlowLayoutPanel aren't aligned like those at design time

Here is the panel prior to programmatic insertion:

The labels at runtime before programmatic add

And after:

The labels after programmatic insertion

I've added other lines copying from the Review label styling hoping it was a padding or margins issue. Unfortunately, that doesn't appear to be the case. To clarify, the FlowLayoutPanel itself extends to the right a good distance beyond what the new label should need as shown here:

Bounds of FlowLayoutPanel

All the other Labels are AutoSize enabled.

Here's the code for generation and insertion:

Label newLabel = new Label();
newLabel.Name = optionString;
newLabel.Text = type;
newLabel.Font = ReviewLabel.Font; // just a random label. only thing that matters is consistent styling.
newLabel.ForeColor = ReviewLabel.ForeColor;
newLabel.Margin = ReviewLabel.Margin;
newLabel.Padding = ReviewLabel.Padding;

LabelsPanel.Controls.Add(typeLabel);

optionString is type with the spaces removed. type's value is 'Terms Of Service.' Thanks for any help.

Edit: Here's illustrating how much space there is if I define a Label at design time by just dragging a Label from the controls panel onto the form and setting the Size and Text properties.

Design time Terms label

Runtime Terms label

Upvotes: 1

Views: 81

Answers (2)

Idle_Mind
Idle_Mind

Reputation: 39122

See the Note at Label.AutoSize():

When added to a form using the designer, the default value is true. When instantiated from code, the default value is false.

So you probably need to add:

newLabel.AutoSize = true;

Upvotes: 3

Bigsby
Bigsby

Reputation: 952

It appears that AutoSize on Label controls aren't set to true by default when you new one up in code. Setting that solved the issue. While consistent with how booleans default values behave, it's different from the default behavior you see when you interact with the designer. That was the disconnect.

Upvotes: 1

Related Questions