Formatting a text box

This short code example will show how to format a text box for numeric values

Currently, we only show how to format for percent values... but we hope to expand it.

Related Articles

... and you 'll find more on the NET Development Menu

Public Class Form1
    Dim TextBox1_DefaultValue As Decimal = 0
 
 
    Private Sub Form1_Load(ByVal sender As ObjectByVal e As System.EventArgsHandles Me.Load
        Me.TextBox1.Text = String.Format("{0:p}", TextBox1_DefaultValue)
    End Sub
 
    ''' <summary>
    ''' shows how to format a text box as a percentage value
    ''' </summary>
    Private Sub TextBox1_Validating(ByVal sender As ObjectByVal e As System.ComponentModel.CancelEventArgsHandles TextBox1.Validating
        'if the value is not numeric, change it to the default value and exit
        If Not IsNumeric(Me.TextBox1.Text) Then
            MsgBox("The value for Text Box 1 must be numeric")
            Me.TextBox1.Text = String.Format("{0:p}", TextBox1_DefaultValue)
            Exit Sub
        End If
 
        'convert the value to numeric
        Dim dValue As Decimal = Me.TextBox1.Text
 
        'divide by 100 to get a 'percent' value
        dValue = dValue / 100
 
        'format the value and assign it to the text box
        Me.TextBox1.Text = String.Format("{0:p}", dValue)
 
    End Sub
 
End Class
 

RealWorldCode gives developers practical, real‑world solutions with clean, working code — no fluff, no theory, just answers.
Links
Home
Knowledge Areas
Sitemap
Contact
Et cetera
Privacy Policy
Terms and Conditions
Cookie Preferences