首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从文本框中删除数字

从文本框中删除数字
EN

Stack Overflow用户
提问于 2014-03-12 20:04:07
回答 4查看 121关注 0票数 0

尝试使用以下类将文本框限制为仅文本:

但是,它会看到它不是文本和e.Handled是假的,而是将数字留在文本框中。我怎么才能把它移除?

代码语言:javascript
运行
复制
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
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2014-03-12 21:27:49

我就这样解决了

代码语言:javascript
运行
复制
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
EN

Stack Overflow用户

发布于 2014-03-12 20:36:09

如果您设置了Handled = False,它会将事件发送到默认要处理的操作系统。因此,您希望相反的内容是真的,以阻止某些内容被输入到文本框中。

所以你想..。

代码语言:javascript
运行
复制
e.Handled = Not Char.IsLetter(c)
'if the character is not a letter then handle it (i.e. stop)

您还需要将上面的语句更改为Back和Delete键为False。

票数 0
EN

Stack Overflow用户

发布于 2014-03-13 01:52:38

下面是如何处理文本框中限制文本的方法。实际上非常简单,我使用了textbox按键处理程序。我还将包括一张图片,向你展示如何达到它。

请注意,"AllowedChars“是用于确定要”允许“用户输入文本框的字符的变量。如果他们试图按下任何其他键,它就不会进入文本框。

使用这种方法,它还允许对大写字母使用backspace和shift键。

代码语言:javascript
运行
复制
 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键,那么只需将代码的这一部分删除如下:

代码语言:javascript
运行
复制
    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

还请注意,这并不会阻止复制和粘贴到表单中,因此在包含操作/submits/按钮时,仍然希望引入错误的预防方法(但是要声明lol)。

此时的图片将指向keypress事件处理程序。

希望这能帮到你!干杯:)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22362596

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档