在 vb.net 中使用 get 和 set 属性 的文本框按键事件

Keypress event of textbox using get and set property in vb.net

这是我的代码,因为我想使用字符而不是数字来验证我的文本框,所以我使用按键方法 但我想将它与 get 一起使用,并使用 try catch 块设置 属性 来传递按键事件的值。但是我做不到

Public Class Form1
Property validatefirstname() As String
    Get
        Return TextBox1.Text
    End Get
    Set(ByVal value As String)
        Try
            If (value <> "") Then
                TextBox1.Text = value
            Else
                MessageBox.Show("please input firstname")
            End If

        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
    End Set
End Property
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
    If Asc(e.KeyChar) < 65 Or Asc(e.KeyChar) > 90 And Asc(e.KeyChar) < 97 Or Asc(e.KeyChar) > 122 Then
        e.Handled = True

        MessageBox.Show("enter only alpha")
    End If
End Sub
End Class

试试这个,它会为你工作

 Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress

     If System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "[^a-zA-Z\b]") Then
           e.Handled = True
        End If

        End If
    End Sub