Hi @soLo Lz , You can refer to the following code.
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
Dim text As String = TextBox1.Text
Dim cursorPosition As Integer = TextBox1.SelectionStart
Dim digitsOnly As String = Regex.Replace(text, "\D", "")
Dim formattedText As String = String.Empty
If digitsOnly.Length >= 2 AndAlso digitsOnly.Length <= 3 Then
formattedText = Regex.Replace(digitsOnly, "(.{2})(.+)?", "$1-$2")
ElseIf digitsOnly.Length >= 4 Then
formattedText = Regex.Replace(digitsOnly, "(.{2})(.{2})(.+)?", "$1-$2-$3")
Else
formattedText = digitsOnly
End If
TextBox1.Text = formattedText
TextBox1.SelectionStart = cursorPosition + 1
End Sub
Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown
If e.KeyCode = Keys.Back Then
Dim text As String = TextBox1.Text
Dim cursorPosition As Integer = TextBox1.SelectionStart
If cursorPosition > 1 AndAlso text(cursorPosition - 2) = "-" Then
TextBox1.Text = text.Remove(cursorPosition - 2, 2)
TextBox1.SelectionStart = cursorPosition - 2
e.SuppressKeyPress = True
ElseIf cursorPosition = text.Length AndAlso text.EndsWith("-") Then
TextBox1.Text = text.Remove(text.Length - 1)
TextBox1.SelectionStart = cursorPosition - 1
e.SuppressKeyPress = True
End If
End If
End Sub
Best Regards.
Jiachen Li
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.