views:

228

answers:

3

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.

+1  A: 

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.

Nick
how does the length of the text relate to the height of the label?
@bmutch: Those methods return both the width and height, so you can discard the width and use the height value.
Zach Johnson
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.
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
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.
I need ot know the correc height of the label so I can place another one underneath it.
Edited with one more possible option (TextBox)
Nick
I tried to use textbox but it stays the same width no matter what text is in it, despite autosize=true
+1  A: 

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)

Zach Johnson
A: 

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.