Reputation: 5373
Background:
I have a TableLayoutPanel
placed in a UserControl
, which then is placed in SplitContainer
. Rows are added programmatically. TableLayoutPanel
is anchored Top|Left|Right
, so after rows are added, its height is recalculated and it expands downward.
Inside the TableLayoutPanel
, there are two columns. The size of the first column is Absolute
, the size of the second column is set to AutoSize
.
In every cell, there is a Label
. All labels in the second column are defined as follows:
Label vName = new Label();
vName.AutoSize = true;
vName.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom;
vName.Margin = new Padding(3);
vName.TextAlign = ContentAlignment.MiddleLeft;
vName.Name = "controlName";
vName.Text = "Some text here";
vName.DoubleClick += new EventHandler(vName_DoubleClick);
vName.Dock = DockStyle.None;
The problem:
Usually, everything works all right, labels resize and everything, except for one strange scenario:
"immoballizes the device (33.33%)"
, width of TableLauoutPanel
's second column is set exactly, so all text is shown in one line.UserControl
is resized: width decreases, so the label should resize, and the text in a label should wrap.UserControl
is resized: the width decreases further.The same thing happens when the TableLayoutPanel
's width increases, but always only if there is a difference of one pixel (between wrapping/not wrapping text).
Also, changing Dock
and/or Anchor
and/or BorderStyle
properties of labels doesn't work (I probably tried all possible combinations...)
This picture illustrates the issue a little:
Upvotes: 1
Views: 3397
Reputation: 5373
Apparently it is a label issue: when autosizing, it wasn't measuring text correctly and sometimes there was a one pixel difference. I've found a strange workaround, though, if someone knows something better please enlighten me.
This way text in my labels wraps correctly every time and everything is autosized properly:
void tableLayoutPanel1_Resize(object sender, EventArgs e)
{
float fWidth = tableLayoutPanel1.GetColumnWidths()[1];
foreach (Control ctr in tableLayoutPanel1.Controls)
{
if (ctr is Label && ctr.Name.Contains("vName_"))
{
// -7 for margins
Size s = TextRenderer.MeasureText(ctr.Text, ctr.Font, new Size((int)fWidth - 7,1000),
TextFormatFlags.VerticalCenter
| TextFormatFlags.Left
| TextFormatFlags.NoPadding
| TextFormatFlags.WordBreak);
if(!ctr.MaximumSize.Equals(s))
ctr.MaximumSize = new Size(s.Width, s.Height);
}
}
}
Upvotes: 1