Dynamic Labels

samsmithnz

Senior Contributor
Joined
Jul 22, 2003
Messages
1,038
Location
Boston
I was wondering if there was anyway in .NET to dynamically size a label depending on how big the text is...
 
Unfortunetly that property doesn't allow me to wrap text, or even make the label show more than one line at a time...
 
Override the OnPaint method of the form:
Code:
protected override void OnPaint(PaintEventArgs e)
{
     SizeF len = new SizeF();
     len = e.Graphics.MeasureString(this.label1.Text.Trim(),this.label1.Font);                              
     this.label1.Width = Convert.ToInt32(len.Width);
     base.OnPaint (e);
}
 
Interesting i was looking at the same type of thing myself - but the method you have put requires a call to invalidate the form whenever the label text is updated to resize the label, but a good starting point :) cheers
 
Well if the labels(s) are repeatedly updated then he needs to extend a label and override the label's OnPaint method with similar logic as that provided. When the label needs repainting call label.Invalidate() followed by label.Update() for an immediate repaint of the label.

Invalidate() marks the control as dirty so it will be repainted when the next WM_PAINT message is sent. Update() sends a WM_PAINT message.

At least I think that's what need to be done.
 
Last edited:
I had a label that used word wrap and had to be resized vertically based on the amount of text it contained. I created a graphics object and used the measurestring method to find the height (the measurestring method has an overload that accepts the maximum width). Here is my code:

Visual Basic:
Dim g As Graphics = lblHelp.CreateGraphics
lblHelp.Height = CInt(g.MeasureString(lblHelp.Text, _
    lblHelp.Font, lblHelp.Width).Height)

If you need a resusable label, you could inherit the label control, override the .Text property, and in the set block measure the size of the text as I did in the code above, and resize the control accordingly. You will also want to resize the height if the .Width property is changed. Here is a quick example:

Visual Basic:
Public Class BetterAutoSizeLabel
    Inherits Label
    Private _Autosize As Boolean

    Public Property VerticalAutoSize() As Boolean
        Get
            Return _Autosize
        End Get
        Set(ByVal Value As Boolean)
            _Autosize = Value

        End Set
    End Property
    Public Overrides Property Text() As String
        Get
            Return MyBase.Text
        End Get
        Set(ByVal Value As String)
            If _Autosize Then Me.Height = CInt(Me.CreateGraphics.MeasureString(Value, Me.Font, Me.Width).Height())
            MyBase.Text = Value
        End Set
    End Property
End Class
 
Back
Top