これが私が書いたコードです。これにより、ユーザーは削除でき、必要に応じてテキストボックスを空白にすることができます。ユーザーが許可されていない文字を入力したときに処理し、ユーザーがテキストボックスにテキストを貼り付けたときにも処理します。ユーザーが有効な文字と無効な文字が混在する文字列をボックスに貼り付けると、有効な文字がテキストボックスに表示され、無効な文字は表示されません。
また、カーソルが正常に動作することを保証するロジックもあります。(テキストを新しい値に設定する際の問題は、カーソルが最初に戻ることです。このコードは元の位置を追跡し、削除された無効な文字を考慮して調整を行います。)
このコードは、任意のテキストボックスの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
注-多数のテキストボックスに対してこれを行う必要がある場合は、テキストボックスへの参照をパラメーターとして受け入れるサブを作成することにより、これの汎用バージョンを作成できます。次に、TextChangedイベントからsubを呼び出すだけです。