Here is the code I wrote. It allows the user to delete, and the user can make the text field empty if he wants. It processes when the user enters a forbidden character, and also processes when the user inserts text into a text field. If the user inserts a string into a field that is a combination of valid and invalid characters, the valid characters will be displayed in the text box, and the characters will not be invalid.
It also has logic to ensure that the cursor behaves normally. (The problem with setting the text to a new value is that the cursor moves to the beginning. This code tracks the starting position and makes adjustments to the account for any invalid characters that are deleted.)
This code can be placed in the TextChaned event of any text field. Remember to change the name from TextBox1 to match your text box.
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
Note. If you need to do this for a bunch of text fields, you can create a general-purpose version by creating a subsection that takes a link to the text field as a parameter. Then you only need to call sub from the TextChanged event.
Allen
source share