Auto Resize Label Height to Accomodate Text

  • Thread starter Thread starter Wenlei Fang
  • Start date Start date
Private Sub sumform_Paint(ByVal sender As Object, ByVal e As
System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
Dim g As Graphics = Me.lbltext1.CreateGraphics()
Dim h As Integer = Me.lbltext1.Height
If Me.lblText1.Text <> "" Then

Me.lblText1.Height = _
CInt( _
g.MeasureString( _
Me.lblText1.Text, _
Me.lblText1.Font, _
Me.lblText1.Width _
).Height _
)
g.Dispose()

Me.Height += Me.lbltext1.Height - h ' you dont need this
line if you don't want to increase the form's height
End If
End Sub

Ahmed
 
Other code didn't work for me... I used this different approach...

Instead of using a label, use a textbox. Change borderstyle to none, Multiline to True, ReadOnly to true, BackColor to Control color to emulate a label. (maybe edit a few other properties to your liking...

'for line count in text box
Const EM_GETLINECOUNT As Integer = &HBA
Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As Integer, _
ByVal lParam As Integer) As Integer

Sub AutoHeight(ByVal txtBox As TextBox)
Dim g As Graphics = Me.CreateGraphics
'get length of text
Dim length As Integer = g.MeasureString(txtBox.Text, txtBox.Font).Width
'get height of text
Dim rowHeight As Integer = g.MeasureString("M", txtBox.Font).Height

'if the length of the text is greater than the textbox...
If length > txtBox.Width Then
'...there are multiple rows so get the number of lines in the text box
Dim rows As Integer = SendMessage(txtBox.Handle, EM_GETLINECOUNT, 0, 0)
txtBox.Height = rows * rowHeight
Else
'...there is only one row
txtBox.Height = rowHeight
End If
g.Dispose()
End Sub

Now to use it,

Private Sub txt_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles txt.TextChanged
AutoHeight(txt)
End Sub
Anybody knows how to accomplish this?

User submitted from AEWNET (http://www.aewnet.com/)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Back
Top