I tried below code:
Private Sub txtName_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtName.KeyPress
' allow upper and lower case A-Z, and backspace
If Not Chr(KeyAscii) Like "[A-Za-z]" And KeyAscii <> 8 Then KeyAscii = 0
End Sub
But it gives:
‘KeyAscii’ is not declared. It may be inaccessible due to its protection level.
Any idea on how to allow alphabet only ?
It looks like you tried to translate a VB6 code verbatim. You need to re-learn the language, VB.NET is completely different in anything but name.
In your particular case,
KeyAsciihas been replaced by theKeyPressedEventArgswhich has two members:KeyCharandHandled.Furthermore, .NET distinguishes between characters and strings (= collection of characters), you cannot simply take a character and apply the
Likeoperator to it, nor should you.Instead, do the following:
Setting
HandledtoTruehas generally the same effect as settingKeyAsciito 0 in VB6 (read the documentation!).Furthermore, since you’re obviously just switching, make sure to enable both
Option ExplicitandOption Strictin the project options, as well as making it the default for further projects in the Visual Studio settings. This helps catching quite a lot of errors for you.Finally, this code is bad for usability. It’s generally accepted that fields should not constrain user input in such a way (and it’s also not safe: what if the user uses copy&paste to enter invalid text?). Instead, you should test the validity of the input in the textbox’
Validatingevent, since it exists this very purpose.