Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

Override the OnPaint method of the form:

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);
}

Posted (edited)

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.

Edited by pas30339
  • Leaders
Posted

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:

 

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:

 

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

[sIGPIC]e[/sIGPIC]

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...