VB .Net autofill dash(-) in TextBox

soLo Lz 41 Reputation points
2023-05-25T05:15:31.5466667+00:00

I want to make an output like this in vb. net TextBox.

ex. account number : 01-12-001

If I type 01, it will output 01-, then 01-12 ----> output 01-12-.

On deleting text, ex. deletion of the last 3 character 01-12-001 ----> output 01-12, if will automatic delete the dash (-).

Thank you....

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,374 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,570 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Jiachen Li-MSFT 26,506 Reputation points Microsoft Vendor
    2023-05-25T09:58:38.6666667+00:00

    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.

    0 comments No comments