How can i control multiply textbox only allow write numeric and show "-" on beginning

Tian 40 Reputation points
2024-02-29T09:17:28.0733333+00:00

here is my code Private Sub textBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles textBox1.KeyPress If Not (Char.IsDigit(e.KeyChar) OrElse e.KeyChar = "-" OrElse e.KeyChar = ChrW(Keys.Back) OrElse e.KeyChar = ChrW(Keys.Delete)) Then ' Ignore the keypress event e.Handled = True End If If e.KeyChar = "-" AndAlso (TryCast(sender, TextBox).Text <> "" AndAlso TryCast(sender, TextBox).SelectionStart <> 0) Then ' Ignore the keypress event e.Handled = True End If End Sub

Developer technologies | VB
{count} votes

Answer accepted by question author
  1. Jiachen Li-MSFT 34,231 Reputation points Microsoft External Staff
    2024-02-29T10:01:57.5433333+00:00

    Hi @Tian ,

    Please try the following code to ensure that only one - is allowed at the beginning and - only allowed at the beginning.

    Also allow Backspace and Delete keys.

    Private Sub textBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles textBox1.KeyPress
        Dim textBox As TextBox = TryCast(sender, TextBox)
    
        ' Allow digits, "-", Backspace, and Delete
        If Not (Char.IsDigit(e.KeyChar) OrElse e.KeyChar = "-" OrElse e.KeyChar = ChrW(Keys.Back) OrElse e.KeyChar = ChrW(Keys.Delete)) Then
            e.Handled = True
        End If
    
        ' Allow "-" only at the beginning and prevent more than one "-"
        If e.KeyChar = "-" AndAlso (textBox.Text <> "" OrElse textBox.SelectionStart <> 0 OrElse textBox.Text.Contains("-")) Then
            e.Handled = True
        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 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.