0

以下のコードを試しました:

 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

しかし、それは与えます:

「KeyAscii」は宣言されていません。保護レベルにより、アクセスできない場合があります。

アルファベットのみを許可する方法について何か考えはありますか?

4

5 に答える 5

5

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, KeyAscii has been replaced by the KeyPressedEventArgs which has two members: KeyChar and Handled.

Furthermore, .NET distinguishes between characters and strings (= collection of characters), you cannot simply take a character and apply the Like operator to it, nor should you.

Instead, do the following:

If Character.IsLetter(e.KeyChar) Then
    e.Handle = True
End If

Setting Handled to True has generally the same effect as setting KeyAscii to 0 in VB6 (read the documentation!).

Furthermore, since you’re obviously just switching, make sure to enable both Option Explicit and Option Strict in 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’ Validating event, since it exists this very purpose.

于 2012-06-10T08:01:34.153 に答える
2

次の正規表現を使用する必要があります。

Dim reg_exp As New RegExp
reg_exp.Pattern = "^[a-zA-Z]*$"
If reg_exp.Test(txtName.Text.Trim()) Then
   MessageBox.Show("Input name is correct")
Else
   MessageBox.Show("Input name is not correct")
End If
于 2012-06-10T08:04:57.140 に答える
1
Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As     System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress

Dim keyAscii As Char
keyAscii = e.KeyChar

        If keyAscii > Chr(64) And keyAscii < Chr(91) Then
        'char is A-Z

    End If

    If keyAscii > Chr(96) And keyAscii < Chr(123) Then
        'char is a-z
    End If
End Sub
于 2012-06-10T08:24:33.047 に答える
1

Where is KeyAscii defined? It looks like it's out of scope.

As you can't just pass it in as a parameter, try declaring it globally first. Then you should be able to access it inside your method.

Disclaimer: Whilst I've used it before, my knowledge of VB.NET is very limited.

于 2012-06-10T08:01:25.180 に答える
0
If (Microsoft.VisualBasic.Asc(e.KeyChar) < 65) _
 Or (Microsoft.VisualBasic.Asc(e.KeyChar) > 122) Then
e.Handled = True
End If
If (Microsoft.VisualBasic.Asc(e.KeyChar) = 8) Then
e.Handled = False
End If
于 2015-02-20T04:04:30.323 に答える