In vb.net, 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
txt_mobile_phone.Text = s
txt_mobile_phone.SelectionStart = txt_mobile_phone.Text.Length -1
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, _ AcEmpNo.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.