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.