尝试使用以下类将文本框限制为仅文本:
然而,它看到它不是文本而e.Handled是假的,但是它将数字保留在文本框中。我该如何删除它?
Public Class LettersOnlyTextbox
Inherits TextBox
Public Class LettersOnlyTextbox
Inherits TextBox
Protected Overrides Sub onkeydown(e As System.Windows.Forms.KeyEventArgs)
Dim c = Convert.ToChar(e.KeyValue)
Select Case e.KeyCode
Case Keys.Back, Keys.Delete
e.Handled = False
Case Else
e.Handled = Not Char.IsLetter(c)
End Select
End Sub
End Class
答案 0 :(得分:1)
我能够以这种方式解决它
Protected Overrides Sub onkeydown(e As System.Windows.Forms.KeyEventArgs)
Dim c = Convert.ToChar(e.KeyValue)
Select Case e.KeyCode
Case Keys.Back, Keys.Delete
e.Handled = False
Case Else
If Not Char.IsLetter(c) Then
e.SuppressKeyPress = True
End If
End Select
End Sub
答案 1 :(得分:0)
如果设置Handled = False,它会将事件发送到操作系统以进行默认处理。所以,你希望在文本框中输入一些东西是正确的。
因此,你想......
e.Handled = Not Char.IsLetter(c)
'if the character is not a letter then handle it (i.e. stop)
您还希望将Back和Delete键上面的语句更改为False
答案 2 :(得分:0)
这就是我如何处理限制文本框中文本的方法。它实际上非常简单,我使用文本框按键处理程序。我还会附上一张图片,告诉你如何到达它。
请注意" AllowedChars "是用于确定您想要的字符的变量"允许"用户能够进入文本框。如果他们试图按任何其他键,它只是不会进入文本框。
使用这种方法,它还允许使用退格键和大写字母的shift键。
Private Sub Textbox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles Textbox1.KeyPress
Dim AllowedChars As String = "abcdefghijklmnopqrstuvwxyz" 'Change the value of this variable to suit your needs.
If e.KeyChar <> ControlChars.Back and ModifierKeys <> Keys.Shift Then
If AllowedChars.IndexOf(e.KeyChar) = -1 Then
e.Handled = True 'This is what prevents the keys from being entered into the textbox
Else
End If
End If
End Sub
如果您不希望允许退格键或Shift键,则只需删除该部分代码:
If AllowedChars.IndexOf(e.KeyChar) = -1 Then
e.Handled = True 'This is what prevents the keys from being entered into the textbox
Else
End If
另请注意,这不会阻止复制和粘贴到表单中,因此您仍然希望在包含操作/提交/按钮时放入错误预防方法(但是您想要声明它lol)。
此时的图片将引导您进入按键事件处理程序。
希望这会对你有所帮助!干杯:)
答案 3 :(得分:0)
Private Sub MyTextBox_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles MyTextBox.KeyPress
If Not IsNumeric(e.KeyChar) And Not e.KeyChar = ChrW(Keys.Back) Then
e.Handled = True
End If
结束子