Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically adding Label to Windows Form (Length of label?)

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.

like image 313
Wilson Avatar asked Jul 18 '12 22:07

Wilson


3 Answers

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.

like image 162
LarsTech Avatar answered Oct 27 '22 10:10

LarsTech


Try the property AutoSize = true;

MSDN refs

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;
like image 22
Steve Avatar answered Oct 27 '22 10:10

Steve


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:

  • msdn.microsoft.com - Label.AutoSize Property (System.Windows.Forms)

Documentation regarding Graphics.MeasureString can be found here:

  • msdn.microsoft.com - Graphics.MeasureString Method (String, Font) (System.Drawing)
like image 45
Filip Roséen - refp Avatar answered Oct 27 '22 10:10

Filip Roséen - refp