2

I am trying to validate wether a number is a decimal in Visual Basic. The results I get when the number is valid the msgBox shows. When it is not valid, I don't receive the msgBox and the program crashes with an error message that number has to be less than infinity.

I tried adding another If Not IsNumeric(txt1.text) then -- But received the same results.

Where did i go wrong?

If IsNumeric(txt1.text) Then msgBox("good") Else msgBox("not good") End If 
1
  • That code should work. Can you post the exact error message? Commented Nov 2, 2010 at 16:07

4 Answers 4

8

Try using Double.TryParse or Decimal.TryParse instead of IsNumeric.

Dim result as Double = 0.0 if Double.TryParse(txt1.text, result) then ' valid entry else ' invalid entry end if 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this was the easiest version to understand.
1

I have just had to write a function which restricts input to a text box to valid decimal values, and I came up with the following:

 Private Sub validateDecimalTextBox(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) handles myTextBox.keyPress Dim textBox As TextBox = DirectCast(sender, TextBox) If Not (Char.IsDigit(e.KeyChar) Or Char.IsControl(e.KeyChar) Or (e.KeyChar = "." And textBox.Text.IndexOf(".") < 0) Or (e.KeyChar = "-" And textBox.Text.Length = 0)) Then e.Handled = True End If End Sub 

This should restrict user input to decimal values, allowing negative values as well.

If you restrict the user inputs then when you get the value out from the text box you can be more confident that it is valid.

This solution is not complete however as it would allow a user to enter just "-" in the text box which would (presumably) not be a valid input for you. Therefore you can use the solutions that others have mentioned and use any of the following in a sensible way.

double.parse, double.tryparse isNumeric() 

My personal preference would be for isNumeric() but the choice is really up to you.

Comments

0

You can ignore characters in the textbox's keypress event, like:

Private Sub txtValue_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtValue.KeyPress If Not Char.IsDigit(e.KeyChar) Then If Not (e.KeyChar = vbBack) Then e.Handled = True End If End If End Sub 

not sure which version of VB you're using, assuming it's .NET

Comments

0

You can also use Textbox Keypress event. i.e

Private Sub Textbox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Textbox1.KeyPress If (e.KeyChar < "0" Or e.KeyChar > "9") And e.KeyChar <> "." And e.KeyChar <> ControlChars.Back Then e.Handled = True Else If e.KeyChar = "." Then If Textbox1.Text.Contains(".") Then Beep() e.Handled = True End If End If End If End Sub 

I hope this helps.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.