Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and the Yahoo Answers website is now in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Visual Basic Coding Problem?

I am trying to write a code so that only numeric values may be entered into two text boxes.

A message box appears saying that you must use a number if the user does not. But as soon as I close the message box out in debug it switches screens to the code and on the line "Subtotal.Text = "$" & BasePrice.Text + TotalDecimal" it says "InvalidCastException was unhandled:Conversion from string "a" to type 'Double'is not valid."

What is the problem here?

My Code:

Dim TotalDecimal As Integer

Dim Value As Integer

'Find Price

If TradeInValue.Text = "" Then

TradeInValue.Text = 0

End If

If StandardRadio.Checked Then

TotalDecimal += STANDARDPRICEDECIMAL

ElseIf PearlizedRadio.Checked Then

TotalDecimal += PEARLIZEDPRICEDECIMAL

ElseIf CustomizedRadio.Checked Then

TotalDecimal += CUSTOMIZEDPRICEDECIMAL

End If

If StereoCheck.Checked Then

TotalDecimal += STEREOPRICEDECIMAL

End If

If LeatherCheck.Checked Then

TotalDecimal += LEATHERPRICEDECIMAL

End If

If ComputerCheck.Checked Then

TotalDecimal += COMPUTERPRICEDECIMAL

End If

If Integer.TryParse(BasePrice.Text, Value) Then

'Contents can be computed

Else

MessageBox.Show("Error. Please input numbers only in Base Price.")

End If

If Integer.TryParse(TradeInValue.Text, Value) Then

'Contents can be computed

Else

MessageBox.Show("Error. Please input numbers only in Trade-In Value")

End If

'Output formulas

Subtotal.Text = "$" & BasePrice.Text + TotalDecimal

Total.Text = "$" & Subtotal.Text + (Subtotal.Text * 0.08)

AmountDue.Text = "$" & Total.Text - TradeInValue.Text

End Sub

Update:

I tried Saswata and Women's idea and the error went away but the computations are coming up wrong in output.

Offline, your solution did not get the error message to go away. It's not in the error list it's on the code screen itself as a pop-up and prevents me from running the program or entering debug.

4 Answers

Relevance
  • t
    Lv 5
    9 years ago
    Favorite Answer

    Only a VB question can get so many wrong answers.

    The fault is with the logic. This is the current, incorrect logic:

        If can't compute BasePrice, show error message.

        If can't compute TradeInValue, show error message.

        Compute the total amount.

    The code attempts to compute the total amount whether or not it detected an error in the two checks. If the input is "asdfgh" and "qwerty", it will display the error messages but attempt to calculate the totals nonetheless, hence the crash.

    The solution is to calculate the totals only if both strings were parsed successfully. I did this by using an ElseIf for the second check and placing the code that calculates the totals in an Else block. It has the side effect of displaying only one error message even if both inputs are invalid, which is good in my opinion – multiple MessageBoxes one after the other are annoying.

    Side note:

    You should use Doubles instead of Integers like @Offline mentioned. It will let your program accept decimals instead of just whole numbers.

    Here is the corrected code:

        Dim ParsedBasePrice As Double

        Dim ParsedTradeInValue As Double

        If Not Double.TryParse(BasePrice.Text, ParsedBasePrice) Then

            'BasePrice cannot be computed.

            MessageBox.Show("Error. Please input numbers only in Base Price.")

        ElseIf Not Double.TryParse(TradeInValue.Text, ParsedTradeInValue) Then

            'Only checks TradeInValue if successfully parsed BasePrice.

            'TradeInValue cannot be computed.

            MessageBox.Show("Error. Please input numbers only in Trade-In Value")

        Else

            'Only do calculations if successfully parsed both BasePrice and TradeInValue.

            Subtotal.Text = "$" & ParsedBasePrice + TotalDecimal

            Dim GrandTotal As Double = (ParsedBasePrice + TotalDecimal) * 1.08

            Total.Text = "$" & GrandTotal

            AmountDue.Text = "$" & GrandTotal - ParsedTradeInValue

        End If

  • Anonymous
    9 years ago

    Your problem is that you are using variables that are declared as integers but are trying to treat them as doubles. Integers cannot have decimals in them and any division/multiplication that results in a decimal will simply kick out anything past the decimal point.

    Replace:

    Dim TotalDecimal As Integer

    Dim Value As Integer

    With:

    Dim TotalDecimal As Double

    Dim Value As Double

    Replace:

    If Integer.TryParse(BasePrice.Text, Value) Then

    With:

    If Double.TryParse(BasePrice.Text, Value) Then

    Replace:

    If Integer.TryParse(TradeInValue.Text, Value) Then

    With:

    If Double.TryParse(TradeInValue.Text, Value) Then

    I believe that should fix your problems but if something still doesn't work properly. Post any new errors (if there are any) and if it's still the same error, I'll just have to try to duplicate the program and try it myself.

  • 9 years ago

    I have to suspect BasePrice.text needs converted from string to at least integer before being added to TotalDecimal to create the new string Subtotal.Text.

    The message is clearly indicating it is a string at present. It is also clear it will NOT convert it on the fly to allow the addition. Logically, it needs a step converting it first, then creation of the Subtotal.Text string.

    There are several other places one suspects should cause the same difficulty as the variables are used. The next line, for instance, creating the string Total.Text and the one after that creating the string AmountDue.Text.

    I would similarly worry about TradeInValue.Text except that it can be evaluated the way it is as a string, no conversion on the fly needed, and the result is perfectly suitable as a string value. Of course, if it is used later... for instance, in the routine above the fail point, "If Integer.TryParse(TradeInValue.Text, Value)" which seems likely to fail if there is actually some specified value for TradeInValue.Text.

    Added:

    Yep, Saswata's got the same idea, and gives a solution. Good job. Lol, about the solution, not about thinking the same thing!

  • 9 years ago

    There is an error. It should be like this--

    'Output formulas

    Subtotal.Text = "$" & (Val(BasePrice.Text) + Val(TotalDecimal))

    Total.Text = "$" & (Val(Subtotal.Text) + Val(Int(Subtotal.Text) * 0.08))

    AmountDue.Text = "$" & (Val(Total.Text) - Val(TradeInValue.Text))

    Source(s): *ME*
Still have questions? Get your answers by asking now.