Programmatically adding Label to Windows Form (Length of label?)
Solution 1
Try adding the AutoSize property:
namelabel.AutoSize = true;
When you place a label on a form with the design editor, this property defaults to true, but if you create the label in code like you did, the default is false.
Solution 2
Try the property AutoSize = true;
Another way is using the MeasureString method of the Graphics class
Graphics e = nameLabel.CreateGraphics();
SizeF stringSize = new SizeF();
stringSize = e.MeasureString(name, namelabel.Font);
nameLabel.Width = (int)stringSize.Width;
Solution 3
You could use the property Label.AutoSize
to automatically adjust the width of your label to properly fit all the contents stored in Label.Text
.
It's worth mentioning that when creating the label using the design editor this property defaults to true, but when you programmatically creates a label on your own the property defaults to false.
namelabel.AutoSize = true;
Of course you could also manually set the width of your label using something as the below to calculate the required width.
Graphics namelabel_g = namelabel.CreateGraphics ();
namelabel.Width = namelabel_g.MeasureString (
namelabel.Text, namelabel.Font
);
Documentation regarding the use of Label.AutoSize
use can be found on msdn:
Documentation regarding Graphics.MeasureString
can be found here:
Wilson
Updated on July 26, 2022Comments
-
Wilson almost 2 years
In my code, i create a label with the following:
Label namelabel = new Label(); namelabel.Location = new Point(13, 13); namelabel.Text = name; this.Controls.Add(namelabel);
The string called name is defined before this, and has a length of around 50 characters. However, only the first 15 are displayed in the label on my form. I tried messing with the MaximumSize of the label but to no avail.