Ruben
Ruben

Reputation: 155

Adjust free space in a TableLayoutPanel

I have a TableLayoutPanel that contains a Label and a ComboBox:

var lblDesignGroup = new Label
{
    Name = "lblDesignGroup",
    Text = "DesignGroup",
    Margin = new Padding(0, 50, 0, 0)
};
tlpCallLog.Controls.Add(lblDesignGroup, 0, 0);

var cboDesignGroup = new ComboBox
{
    Name = "cboDesignGroup",
    DataSource = designGroups,
    DisplayMember = "DesignGroupName",
    ValueMember = "DesignGroupId",
    Margin = new Padding(0, 50, 0, 0),
    DropDownStyle = ComboBoxStyle.DropDownList
};

Once I create them, I setup the TableLayoutPanel as:

tlpCallLog.ColumnStyles.Clear();
for (int i = 0; i < tlpCallLog.ColumnCount; i++)
{
    tlpCallLog.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
}

tlpCallLog.RowStyles.Clear();
for (int i = 0; i < tlpCallLog.RowCount; i++)
{
    tlpCallLog.RowStyles.Add(new RowStyle(SizeType.AutoSize));
}
tlpCallLog.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single;

enter image description here

But for some reason, I have blank space between the Label and the DropDown.
As you can see, the DropDown width adjusts correctly, it does not have any free space, but the Label has it.
I want to remove that space. How can I achieve that?

Upvotes: 2

Views: 437

Answers (1)

Jimi
Jimi

Reputation: 32223

The Label Control auto-sizes in a default layout (when child of a Form, as a standard scenario, since the Form performs its layout when initialized). When created like this, the AutoSize property is set to true because that's the default value, but the Layout is never performed.
When you explicitly set AutoSize = true, then the layout is performed.

Set both the TableLayoutPanel and the Label to AutoSize:

tlpCallLog.AutoSize = true;
tlpCallLog.RowStyles.Clear();
//[...]

var lblDesignGroup = new Label {
    AutoSize = true,
    Name = "lblDesignGroup",
    Text = "DesignGroup",
    Margin = new Padding(0, 53, 0, 0)
};
tlpCallLog.Controls.Add(lblDesignGroup, 0, 0);

var cboDesignGroup = new ComboBox {  
    //[...]
}

I suggest to set the Label's Margin = new Padding(0, 53, 0, 0): 3 pixels down, to align with the ComboBox text. It's a valid measure with (almost) any Font size.

Another suggestion is to set the [Form].AutoScaleMode = AutoScaleMode.Dpi.

TableLayoutPanel AutoSize

Upvotes: 1

Related Questions