user12869441
user12869441

Reputation: 1

Data Type validation in textbox

Trying to make a validation where only letters can be entered into a textbox. I've got that part working, but I would also like the ability for the user to use the backspace button, and I'm not sure how

Private Sub TxtBoxCustForename_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TxtBoxCustForename.KeyPress
   If Asc(e.KeyChar) < 65 Or Asc(e.KeyChar) > 122 Then 'Ensures only letters can be entered by using the ASCII converter'
      e.Handled = True
      MessageBox.Show("You may only input letters")
   End If
End Sub

Upvotes: 0

Views: 264

Answers (4)

jmcilhinney
jmcilhinney

Reputation: 54457

If you're going to use .NET then use .NET.

Private Sub TxtBoxCustForename_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TxtBoxCustForename.KeyPress
    Dim keyChar = e.KeyChar

    If Not Char.IsLetter(keyChar) AndAlso Not Char.IsControl(keyChar) Then
        e.Handled = True

        MessageBox.Show("You may only input letters")
    End If
End Sub

This still doesn;t prevent the user pasting invalid text into the control though, so you still need to handle the Validating event or use a custom control that catches paste operations.

Upvotes: 0

Cla3rk
Cla3rk

Reputation: 31

Rather than using the KeyPress event, use the TextChanged event. Also, I would recommend using the IsNumeric function to test whether it is a number or not.

Private Sub TxtBoxCustForename_KeyPress(sender As Object, e As EventArgs) Handles TxtBoxCustForename.TextChanged
   For Each entry as Char in TxtBoxCustForename.Text
       If IsNumeric(entry) Then
          MessageBox.Show("You may only input letters")
          Exit For
       End If
   Next
End Sub

Upvotes: 0

HackSlash
HackSlash

Reputation: 5813

Input validation is a built-in feature of .NET. You don't need to capture key presses and manually code your own solution.

You might want to use a MaskedTextBox as suggested in this article:

https://learn.microsoft.com/en-us/dotnet/framework/winforms/user-input-validation-in-windows-forms

Upvotes: 1

Brian M Stafford
Brian M Stafford

Reputation: 8868

You can change your If statement like this:

If (Asc(e.KeyChar) < 65 Or Asc(e.KeyChar) > 122) And Asc(e.KeyChar) <> 8 Then

Ascii 8 is the Backspace key.

Upvotes: 0

Related Questions