Kentaro51
Kentaro51

Reputation: 45

problems with variables on Visual Basic

I'm trying to calculate tip using radio buttons and use them to select the percentage but the variable "tip" doesn't transfer over to the next sub and lblTip.text keeps coming up as 0

Here's my code:

Public Class Form1
Dim tip As Double
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
    Me.Close()
End Sub


Private Sub btnDisplay_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDisplay.Click

    Select Case True
        Case rbtnTen.Checked
            tip = 0.1
        Case rbtnFifteen.Checked
            tip = 0.15
        Case rbtnTwenty.Checked
            tip = 0.2
    End Select

End Sub

Private Sub btnCalcTip_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCalcTip.Click
    lblTip.Text = Val(txtBill.Text) * tip
End Sub
End Class

Upvotes: 1

Views: 211

Answers (3)

APrough
APrough

Reputation: 2701

As is, your code works fine, but a couple of things...

  • Use the If..ElseIf..EndIF that everyone mentions.
  • Try not to use Val (It works in this situation, but it may not in all)

As for why you are getting only 0, I was able to replicate that behavior using your existing code, by one of the threefollowing...

  1. Don't click btnDisplay first. In this case, you do not assign a value to tip, so it defaults to 0. Multiply 0 by any amount and you get... 0.
  2. Not having a value in TxtBill. Same reason as #1.
  3. Not have a default value for the radio buttons set, and trying to calculate.

Assuming I put a value in txtBill, choose a tip option and pressed btnDisplay, I get a value.

I would put breaks in and trying to track the values in your variables to see what is going on. You could also probably make btnDisplay and btnCalc do all the work at once (verify that a tip amount has been chosen, and do calc and display results). No point in clicking two buttons.

Upvotes: 1

Have you tried:

lblTip.Text = CStr(CDbl(txtBill.Text) * tip)

How about ElseIf statements instead of your case statement:

If rbtnTen.Checked Then
    tip = 0.1
ElseIf rbtnFifteen.Checked Then
    tip = 0.15
ElseIf rbtnTwenty.Checked Then
    tip = 0.2
EndIf

Upvotes: 0

MunkiPhD
MunkiPhD

Reputation: 3644

Using Val() is usually not recommended (especially in i18n code). It's a carry over from Visual Basic (pre .Net) and it creates all types of funky data when parsing values. It's recommended to clean the string first then parse it, i.e. stripping dollar signs, then parse the value as a single/double.

For more info on Val() look at the corresponding MSDN page.

Upvotes: 0

Related Questions