这是我写的一些代码。它允许用户删除,并且用户可以根据需要将文本框设为空白。它在用户键入不允许的字符时进行处理,并且在用户将文本粘贴到文本框中时也进行处理。如果用户将包含有效字符和无效字符的字符串粘贴到框中,则有效字符将出现在文本框中,而无效字符则不会出现。
它还具有确保游标正常运行的逻辑。(将文本设置为新值的一个问题是光标移回了开头。此代码跟踪原始位置,并进行调整以解决任何被删除的无效字符。)
这段代码可以放在任何文本框的 TextChaned 事件中。请务必从 TextBox1 更改名称以匹配您的文本框。
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
Dim selStart As Integer = TextBox1.SelectionStart
Dim selMoveLeft As Integer = 0
Dim newStr As String = "" 'Build a new string by copying each valid character from the existing string. The new string starts as blank and valid characters are added 1 at a time.
For i As Integer = 0 To TextBox1.Text.Length - 1
If "0123456789".IndexOf(TextBox1.Text(i)) <> -1 Then 'Characters that are in the allowed set will be added to the new string.
newStr = newStr & TextBox1.Text(i)
ElseIf i < selStart Then 'Characters that are not valid are removed - if these characters are before the cursor, we need to move the cursor left to account for their removal.
selMoveLeft = selMoveLeft + 1
End If
Next
TextBox1.Text = newStr 'Place the new text into the textbox.
TextBox1.SelectionStart = selStart - selMoveLeft 'Move the cursor to the appropriate location.
End Sub
注意 - 如果您必须为一堆文本框执行此操作,您可以通过创建一个接受对文本框的引用作为参数的 sub 来制作通用版本。然后你只需要从 TextChanged 事件中调用 sub。