Make Text Auto Fit Textbox Size - Visual Basic .NET

Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013

The following example describes how to make the text fit and fill all space available in a textbox auto size text

visual basic make text fit textbox size

For this tutorial you need to add a textbox to the form

Add the following declarations below the Public Class Form1

Dim h As String
Dim w As String

Then add the following Paint event handler code:

Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
        Dim orgFont As New Font(TextBox1.Font.Name, TextBox1.Font.Size, TextBox1.Font.Style)
        Dim textSize As New SizeF
        textSize = e.Graphics.MeasureString(TextBox1.Text, orgFont)
        h = textSize.Height
        w = textSize.Width
End Sub

The add the following TextChange event code:

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        TextBox1.Font = New Font(TextBox1.Font.Name, 8, TextBox1.Font.Style)
        TextBox1.BorderStyle = BorderStyle.Fixed3D
        Do Until w > TextBox1.Size.Width - 5 Or TextBox1.Text = Nothing Or h > 182
            TextBox1.Font = New Font(TextBox1.Font.Name, TextBox1.Font.Size + 2, TextBox1.Font.Style)
        TextBox1.BorderStyle = BorderStyle.None
    End Sub

Share This

Home | About | Contact | Privacy Policy

Copyright 2018 - All Rights Reserved.