joe joe - 1 year ago 85 Question

Textbox validation, cursor skipping to the start of the text

In, I have the following code to validate acceptable characters that can be entered into a textbox.

Private Sub txt_mobile_phone_TextChanged(sender As Object, e As EventArgs) Handles txt_mobile_phone.TextChanged

Dim s As String = ""

For Each C As Char In txt_mobile_phone.Text
If (C >= "0" And C <= "9") OrElse (C = " ") OrElse (C = "-") OrElse (C = "+") Then
s &= C
End If

txt_mobile_phone.Text = s

End Sub

The problem is, is that when someone enters an invalid character (for example, an exclamation mark '!'), the cursor position then skips to the start of the text string, and all further characters are entered at the start.Is there a way to make it so that it ignores invalid characters and carries on typing from the end of the string?

If possible, without using
txt_mobile_phone.SelectionStart = txt_mobile_phone.Text.Length -1
as this means that clicking the middle of the string to add to the middle of it will break (which currently is possible)

Answer Source

The issue is that you are firing an event on the TextChanged, that is int he middle of something. For your purpose, to validate entries, you have got the KeyPress event, whereby you have the e.Handle to block entries.

Find the example below, which I applied in my application to accept only numeric and should not accept spaces;

Private Sub txt_mobile_phone_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txt_mobile_phone.KeyPress, _
    ' Accept only numeric values
    If (e.KeyChar < Chr(48) OrElse e.KeyChar > Chr(57)) _
    AndAlso e.KeyChar <> Chr(8) Then
        e.Handled = True
    End If

End Sub

You can also use Char convertor if you don't know the code like;

e.KeyChar = ChrW(Keys.Space)

Hope this helps.