samsmithnz
Senior Contributor
I was wondering if there was anyway in .NET to dynamically size a label depending on how big the text is...
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);
}
Dim g As Graphics = lblHelp.CreateGraphics
lblHelp.Height = CInt(g.MeasureString(lblHelp.Text, _
lblHelp.Font, lblHelp.Width).Height)
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