Pezzzz
Pezzzz

Reputation: 748

limit the range of characters the user can put into a textbox vb.net

I have a textbox in a vb form and I want to limit the range of characters that the user can put into the textbox to:" abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890^-*().". The textbox is to insert SI Units into a database so i need consistent syntax. If the user types an invalid character into the textbox I would like the textbox to refuse to insert it, or remove it straight away, leaving the cursor in the same position within the textbox. I would also like the textbox to replace "/" with "^(-" and place the cursor before this.

I have found some code elsewhere which I have edited to do this but the code is bad, it activates on text changed within the textbox. This causes the code to fail, when the user inputs a disallowed value the code it activates itself when it tries to changes the text within the textbox.

Here is my code, the textbox starts with the contents "enter SI Units" from the form designer.

Private Sub TxtQuantityTextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSIUnit.TextChanged

If txtSIUnit.Text = "Enter SI Units" Then
        Exit Sub
    End If

    Dim charactersAllowed As String = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890^-*()."
    Dim Text As String = txtSIUnit.Text
    Dim Letter As String
    Dim SelectionIndex As Integer = txtSIUnit.SelectionStart
    Dim Change As Integer




    Letter = txtSIUnit.Text.Substring(SelectionIndex - 1, 1)
    If Letter = "/" Then
        Text = Text.Replace(Letter, "^(-")
        SelectionIndex = SelectionIndex - 1
    End If



    Letter = txtSIUnit.Text.Substring(SelectionIndex - 1, 1)
    If charactersAllowed.Contains(Letter) = False Then
        Text = Text.Replace(Letter, String.Empty)
        Change = 1
    End If


    txtSIUnit.Text = Text
    txtSIUnit.Select(SelectionIndex - Change, 0)

    If txtQuantity.Text <> "Enter Quantity" Then
        If cmbStateRateSumRatio.SelectedIndex <> -1 Then
            bttAddQUAtoDatabase.Enabled = True
        End If
    End If

End Sub`

Thanks for you help.

Upvotes: 0

Views: 2389

Answers (2)

Hans Passant
Hans Passant

Reputation: 941515

Use the KeyPress event. Set e.Handled to true if you don't like the character. It's a one-liner:

Private Const AllowedChars = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890^-*()."

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As PressEventArgs) Handles TextBox1.KeyPress
    If e.KeyChar >= " "c AndAlso Not AllowedChars.Contains(e.KeyChar) Then e.Handled = True
End Sub

Upvotes: 1

jzonthemtn
jzonthemtn

Reputation: 3404

In the textbox's KeyDown event, check e.KeyCode. This lets you prevent certain characters from being handled. There's an example on the KeyDown documentation.

Upvotes: 1

Related Questions