Alkatraz Goatz
Alkatraz Goatz

Reputation: 11

How to auto add a leading zero to a digit in a textbox

i have a text box to enter a certain digit , if the entered number is a one digit number i want a leading zero to be added automatically.How could I do this? whats the code for this ?

Please help

Upvotes: 1

Views: 1457

Answers (3)

Pradeep Kumar
Pradeep Kumar

Reputation: 6969

Use the Validating event to be sure that your code will always fire. And use the x2 format to specify that you need 2 digit number.

Private Sub TextBox1_Validating(ByVal sender As Object, ByVal e As CancelEventArgs) Handles TextBox1.Validating
    If IsNumeric(TextBox1.Text) Then
        TextBox1.Text = CInt(TextBox1.Text).ToString("x2")
    End If
End Sub

Upvotes: 2

user1234433222
user1234433222

Reputation: 996

This should work, and it should also have the text start from the end of the textbox.

  Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
    If TextBox1.Text.Length = 1 Then
        TextBox1.Text = "0" + TextBox1.Text
        TextBox1.SelectionStart = TextBox1.TextLength + 1
    End If
End Sub

Upvotes: 0

Claudius
Claudius

Reputation: 1911

Protected Sub TextBox1_TextChanged(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles TextBox1.TextChanged
If TextBox1.Text.Length = 1
   TextBox1.Text = "0" + TextBox1.Text
End if
End Sub

Upvotes: 2

Related Questions