0

My label is wrapping the text due to the length of the text. The height property returns the correct value only if there is a single line. How can I get the correct height?

Thanks.

Solution: I was creating the label dynamically and checking the height then. Later the panel on which the label was residing was added to a form, changing the panel's font and thus also changing the label's font and height.

2
  • The Height property returns the height of the label. If the label is wrapping, but not being resized to fit the text, the height of the label won't change, just the height of the text. Feb 22, 2010 at 19:50
  • The label is being resized, (and it is created dynamically) from MS Help: The height of the control (in pixels), assuming a single line of text is displayed.
    – user263725
    Feb 22, 2010 at 19:55

3 Answers 3

3

The easiest way to get the preferred dimensions of a label is by using Label.GetPreferredSize(Size.Empty). If you wish to get the dimensions constrained by a size, use the same method with a non-empty size: Label.GetPreferredSize(constrainingSize)

1

Option 1: You can use Graphics.MeasureString or TextRenderer.MeasureText. The second one is probably easier for your purposes.

Option 2: If the label is not growing properly to fit the entire text, make sure that the AutoSize property is set to True.

Option 3: Use a TextBox instead of a Label. Set the ReadOnly property to true, and change the backcolor and border to match a Label. Then, set MultiLine = True. That may give you the same effect, but without whatever bug you are seeing.

8
  • how does the length of the text relate to the height of the label?
    – user263725
    Feb 22, 2010 at 22:27
  • @bmutch: Those methods return both the width and height, so you can discard the width and use the height value. Feb 22, 2010 at 22:30
  • The TextRenderer.MeasureText method is giving me the height of a single line of text in the lable, I need the height of the label itself to know where to place the next label underneath it.
    – user263725
    Feb 23, 2010 at 14:21
  • The Label Height property will give you the physical height of the label itself. If you are trying to get the label to fit all the text, make sure the AutoSize property is set to True. If you are trying to find out how big the label needs to be set to in order to fit all the text, then the methods I mentioned will give you that.
    – Nick
    Feb 23, 2010 at 14:37
  • It is autosize. And it is wrapping, I can see it has 2 lines, but the height property is still the same as the labels that are not wrapping.
    – user263725
    Feb 23, 2010 at 14:47
0

Solution: I was creating the label dynamically and checking the height then. Later the panel on which the label was residing was added to a form, changing the panel's font and thus also changing the label's font and height.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.