Frage

I've been struggelig with an embarrassing and annoying little problem in visual basic (I'm, as you probbably see, a beginner). The problem is the error message system for when letters are entered instead of numbers. I get "can't convert from integer to string.

Any help on this would be most appreciated.

Here is my code:

    Dim number1, number2 As Integer
    Dim sum As String

    number1 = InputBox("first value:")
    number2 = InputBox("second value:")
    sum = number1 + number2

    If IsNumeric(sum) Then
        MsgBox("The sum of the numbers " & number1 & " and " & number2 & " is: " & sum)
    ElseIf Not IsNumeric(sum) Then
        MsgBox("You may only type numbers into the fields!, trie again")
    End If

In advance, thank you :)!

War es hilfreich?

Lösung

You are doing the Type conversion wrongly. Improved code:

Dim input1, input2 As String

input1 = InputBox("first value:")
input2 = InputBox("second value:")

If IsNumeric(input1) And IsNumeric(input2) Then
    MsgBox("The sum of the numbers " & input1 & " and " & input2 & " is: " & (Convert.ToInt32(input1) + Convert.ToInt32(input2)).ToString())
Else
    MsgBox("You may only type numbers into the fields!, try again")
End If

InputBox returns strings which you are implicitely converting to Integer by associating them to integer-type variables, thus you provoke an error when inputting non-numeric values. Best way to avoid problems is relying always on the right Type, as shown in the code above: the inputs are strings but IsNumeric takes precisely strings as inputs. Once the right inputs are confirmed, the conversion to the corresponding type (Integer, but you might want to rely on Decimal or Double to account for decimal positions) is performed and the mathematica operation performed with numeric types. Lastly, I am performing a conversion to String (just to keep this answer consistent), although bear in mind that VB.NET performs this conversion (from number to string) implicitely without any problem.

Andere Tipps

Put validation on your number boxes so that they must be numeric and not just on your sum.

If Not IsNumeric(number1) Then
  MsgBox("You may only type numbers into the fields!, try again")
End If

If Not IsNumeric(number2) Then
  MsgBox("You may only type numbers into the fields!, try again")
End If
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top