Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Auto Size textbox 1

Status
Not open for further replies.

l310564

Programmer
Jun 18, 2006
50
GB
Hi,

I have a multiline textbox in which text is inserted from a database. This all works fine but i want the textbox to
expand (height only) when the text is too long to fit in the viewable area.

I have been stuck on this problem for a couple of days now so any suggestions on how this might be acheived will be apprecated.


Cheers,


Hugh
 
Here's a GetLineCount function that can be used to return the linecount (including wrapped lines) of any string using a specific font and width. I can't remember where I saw this originally.

It took me a while to tweak this. (lines*fontheight)+6 seems to work for a range of font sizes.

Code:
TextBox1.Height = (GetLineCount(TextBox1.Text, TextBox1.Font, TextBox1.Width) * (TextBox1.Font.Height)) + 6

Code:
		Shared Function GetLineCount(ByVal vText As String, ByVal vFont As Font, ByVal ControlWidth As Integer) As Integer
			'created to return an accurate line count of a textbox including wrapped lines as well as line breaks

			'build a textbox that can be passed to SendMessage function - note this allows the function to be used with a variety of controls
			Dim tb As New TextBox
			tb.Multiline = True
			tb.WordWrap = True
			tb.Width = ControlWidth
			tb.Font = vFont
			tb.Text = vText

			Dim EM_GETLINECOUNT As Long = &HBA&
			Dim lineCount As Integer = SendMessage(tb.Handle, EM_GETLINECOUNT, 0, 0&)
			Return lineCount
		End Function
 
Thanks for the prompt reply but....

it doesn't like the sendmessage function. what class does this belong to?

Cheers

Hugh
 
You can give this a try..

Code:
    Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) _
    Handles Me.Paint

        Dim lines, cols As Integer
        e.Graphics.MeasureString(TextBox1.Text, TextBox1.Font, _
            New SizeF(TextBox1.Width, 1000), New StringFormat, cols, lines)
        TextBox1.Height = TextBox1.Font.Height * (lines + 1)

    End Sub
 
Oops!

Code:
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		  'used in GetLineCount function

Forgot about that bit.

I've not checked TipGivers code, but I stopped using the MeasureString method for text height as it didn't account for line wraps, only line return characters.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top