0

I am taking a user input a text box and then Validating it as follows:

Val(txt_score1.text)

Then I have to compare it with blank entry in that text box. Like this:

If (Val(txt_score1.Text) = "") Then....

I am receiving a conversion error. Because "" is String whereas Val is returning Integer.

How to overcome this??

HelmBurger
  • 1,168
  • 5
  • 15
  • 35
  • Difficult to give you an answer that will actually help you without knowing what you want to test for. What are you trying to check there, exactly? – Oded Sep 07 '13 at 12:40
  • 1
    I think you are misunderstanding the purpose of the `Val` function. As the error message you are getting is telling you, `Val` takes a string argument and tries to convert it to an integer. It has been a part of the BASIC language for a long time. If you could explain precisely what kind of validation you want to carry out on the text, people could help more – Ken Keenan Sep 07 '13 at 12:40
  • 1
    I think you are looking for [IsNumeric](http://msdn.microsoft.com/en-us/library/6cd3f6w1(v=vs.90).aspx) function. – Victor Zakharov Sep 07 '13 at 12:47

1 Answers1

4

You can use Integer.TryParse to determine if the value is a proper integer:

    Dim x As Integer
    If Integer.TryParse(TextBox1.Text, x) Then
        MessageBox.Show(x)
    Else
        MessageBox.Show("'" + TextBox1.Text + "' is not a valid number")
    End If

If you need to just check for a blank string, you can use String.IsNullOrEmpty on the text itself:

    If String.IsNullOrEmpty(TextBox1.Text) Then
        MessageBox.Show("String is empty")
    End If

Val is a legacy function leftover from VB6 days and has some weird behavior if you don't know about it. I avoid it for this reason. For example, take the following cases and the output they generate:

    MessageBox.Show(Val(""))        '0
    MessageBox.Show(Val("5"))       '5
    MessageBox.Show(Val("5e3"))     '5000
    MessageBox.Show(Val("5xyz"))    '5
John Koerner
  • 37,428
  • 8
  • 84
  • 134