Reputation: 45
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
Reputation: 2701
As is, your code works fine, but a couple of things...
As for why you are getting only 0, I was able to replicate that behavior using your existing code, by one of the threefollowing...
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
Reputation: 5759
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
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