0

I have a text box in VB which is set up to only accept only numeric data, and it works, except in TWO specific cases.

If the user provides a NON NUMERIC CHAR the text box self clears,

However, if the user first provides a number, then provides either '-' or '+'

The text box will accept this as a valid input.

When the user types one more char of ANY TYPE, i.e. number or char

Then the text box 'realises' and will self clear.

I was wondering if this is due to the way VB stores the chars '-' and '+'?

Is the best way around this to just add in the two exceptions, i.e. if '-' or '+' are input then self clear?

Or is there a more elegant solution?

Thank you.

Code:

Private Sub TextBox1_Change()

'Textval used as variable from user input
'Numval becomes textval providing the user input is numerical

Dim textval As String
Dim numval As String

  textval = TextBox1.Text
  If IsNumeric(textval) Then
    numval = textval
  Else
    TextBox1.Text = CStr(numval)
  End If
End Sub
Thom G
  • 87
  • 1
  • 1
  • 10
  • [**This**](http://stackoverflow.com/questions/15423114/checking-to-see-if-text-box-input-is-numeric?rq=1) might be worth reading as it may be what you are looking for. – Trevor Oct 13 '16 at 14:46
  • Using a masked text box could be an alternative solution to what has been suggestted. – Ryan Thomas Oct 13 '16 at 15:27

2 Answers2

0

code vb.net :

If Asc(e.KeyChar) <> 13 AndAlso Asc(e.KeyChar) <> 8 AndAlso Not IsNumeric(e.KeyChar) Then
' your code here 
   e.Handled = True

End If

and you can Replace text : code :

Text = Text.Replace("string", "replace_by_this_string")
Aladein
  • 184
  • 2
  • 13
  • And just where is he getting the `e` argument from in your code you provided? On another note your example of replace is irrelevant in whole, has nothing to do with his question. – Trevor Oct 13 '16 at 14:43
0

If the program requires the user to type only numeric data to the textbox, you should enforce the restriction when the user pressed a key

Use the textbox's KeyDown event:

'Omitting the parameters and Handles keyword
Private Sub textbox_KeyDown()
    'Set the keys you would want to allow in this array
    Dim allowedkeys As Keys() = {Keys.D1, Keys.D2, Keys.D3, Keys.D4, Keys.D5, Keys.D6, Keys.D7, Keys.D8, Keys.D9, Keys.D0, Keys.Back}

    For i = 0 To allowedkeys.Length - 1 'Iterate through the allowed keys array
        If e.KeyCode = allowedkeys(i) Then 'If the key pressed is present in the array...
            Exit Sub 'The check returned a success. Exit and accept the key
        End If
    Next
    e.SuppressKeyPress = True 'Supress all keys that failed the check
End Sub

Don't forget to add more keys that you need! The Space key, the numpad keys, the dot (point) keys?

This way you can remove the check in the Changed event and go directly to numval = textval

Or for those lazy programmers, numval = TextBox1.Text and numval = Val(TextBox1.Text) worked as well

mmgfrcs
  • 16
  • 3