Syntax Error - Cant Calculate - vb.net

I can't figure out whats wrong with my code. The code is supposed to calculate the total cost of an item using cost, quantity and promo code if u have one. It keeps crashing when I put in unused characters such as ! . Any help or improvements would be welcome.
Public Class Form1
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim decDisplayTotal As Decimal
Dim decPrice As Decimal = txtPrice.Text
Dim intQuantity As Integer = txtQuantity.Text
Dim strPromoCode As String = txtPromoCode.Text
decDisplayTotal = decPrice * intQuantity
lblDisplayTotal.Text = "$" & decDisplayTotal
If decPrice < 0 Then
lblDisplayTotal.Text = ("")
txtPrice.Text = Nothing
txtQuantity.Text = Nothing
txtPromoCode.Text = Nothing
MessageBox.Show("Please enter an appropriate price.", "Invalid Input")
End If
If intQuantity < 0 Then
lblDisplayTotal.Text = ("")
txtPrice.Text = Nothing
txtQuantity.Text = Nothing
txtPromoCode.Text = Nothing
MessageBox.Show("Please enter an approriate quantity.", "Invalid Input")
End If
If strPromoCode = ("132") Then
MessageBox.Show("You used a limited time, 10% off code! Watch your price drop 10%!", "10% off")
decDisplayTotal = 0.9 * (decPrice * intQuantity)
lblDisplayTotal.Text = "$" & decDisplayTotal
End If
If strPromoCode = ("129") Then
MessageBox.Show("You used a limited time, 20% off code! Watch your price drop 20%!", "20% off")
decDisplayTotal = 0.8 * (decPrice * intQuantity)
lblDisplayTotal.Text = "$" & decDisplayTotal
End If
If strPromoCode = ("136") Then
MessageBox.Show("You used a limited time, 30% off code! Watch your price drop 30%!", "30% off")
decDisplayTotal = 0.7 * (decPrice * intQuantity)
lblDisplayTotal.Text = "$" & decDisplayTotal
End If
If strPromoCode = ("264") Then
MessageBox.Show("You used a limited time, buy 1 get 1 free code, so watch your total cut in half!", "Buy 1 Get 1 Free")
decDisplayTotal = 0.5 * (decPrice * intQuantity)
lblDisplayTotal.Text = "$" & decDisplayTotal
End If
If strPromoCode = ("125") Then
decDisplayTotal = (decPrice * intQuantity)
lblDisplayTotal.Text = "$" & decDisplayTotal
End If
Try
decPrice = Convert.ToInt16(txtPrice.Text)
Catch ex As Exception
lblDisplayTotal.Text = Nothing
MessageBox.Show("Please enter an acceptable price.", "Invalid Input")
txtPrice.Text = Nothing
End Try
Try
intQuantity = Convert.ToInt16(txtQuantity.Text)
Catch ex As Exception
lblDisplayTotal.Text = Nothing
MessageBox.Show("Please enter an acceptable quanitity.", "Invalid Input")
txtQuantity.Text = Nothing
End Try
Try
strPromoCode = Convert.ToInt16(txtPromoCode.Text)
Catch ex As Exception
lblDisplayTotal.Text = Nothing
MessageBox.Show("Please enter a valid Promo Code.", "Invalid Input")
txtPromoCode.Text = Nothing
End Try
End Sub
Private Sub txtPrice_TextChanged(sender As Object, e As EventArgs) Handles txtPrice.TextChanged
lblDisplayTotal.Text = ("")
End Sub
Private Sub txtQuantity_TextChanged(sender As Object, e As EventArgs) Handles txtQuantity.TextChanged
lblDisplayTotal.Text = ("")
End Sub
Private Sub txtPromoCode_TextChanged(sender As Object, e As EventArgs) Handles txtPromoCode.TextChanged
lblDisplayTotal.Text = ("")
End Sub
End Class

The first thing to understand clearly is that a string is not a number. VB allows this laxity but it bites back in many subtle ways.
I presume that you put the single point in any of your textboxes and then try to use that TEXT as it was a string. Sometime it works sometime not.
The correct approach is to ask the Framework to attempt the conversion and if it fails inform your user of the problem.
So, instead of using the various Convert.ToXXXXx use SomeType.TryParse (I.E. Int32.TryParse)
Dim decPrice As Decimal
Dim intQuantity As Integer
Dim strPromoCode As String
if Not Decimal.TryParse(txtPrice.Text, decPrice) Then
MessageBox.Show("Please type a valid number for Price")
ClearInputs()
return
End if
if Not Int32.TryParse(txtPrice.Text, intQuantity) Then
MessageBox.Show("Please type a valid number for Quantity")
ClearInputs()
return
End if
Private Sub ClearInputs()
lblDisplayTotal.Text = ""
txtPrice.Text = ""
txtQuantity.Text = ""
txtPromoCode.Text = ""
End Sub
Now your typed values are stored in the correct datatype variables and you could proceed with the remainder of your code.....
....
decDisplayTotal = decPrice * intQuantity
lblDisplayTotal.Text = "$" & decDisplayTotal.ToString
....
An important configuration that you need to set for your projects is Option Strict On in your project properties. This configuration will disallow the implicit conversion between strings and numbers and force you to write a more correct code.
And by the way, after the checks on the strPromoCode, you don't need to repeat again the process to convert the strings in the textboxes to the corresponding variables

Related

VB confused by if path

I have VB program which user is to enter grades into using an InputBox. Regardless of user input, a message box (msgbox) stating "Please enter a number" appears. How do I change this to only show this message if a number is not entered?
Option Strict Off
Public Class Form1
Dim totalpointsaccumultator As Object
Private Sub exitButton_Click(sender As Object, e As EventArgs) Handles exitButton.Click
Me.Close()
End Sub
Public Sub assignButton_Click(sender As Object, e As EventArgs) Handles assignButton.Click
Dim inputProjectPoints, inputTestPoints As String
Dim grade, projectpoints, testpoints As String
Dim projectcounter As Integer = 1
Dim testcounter As Integer = 1
Dim isconverted As Boolean
Dim totalpointsaccumulator As Integer
Do While projectcounter < 5
inputProjectPoints = InputBox("Enter the points earned on project " & projectcounter, "Grade Calculator", "0")
inputProjectPoints = projectpoints
isconverted = Integer.TryParse(inputProjectPoints, CInt(projectpoints))
If isconverted Then
totalpointsaccumultator = totalpointsaccumulator + projectpoints
projectcounter = projectcounter + 1
Else
MessageBox.Show("Please enter a number.", "Grade Calculator", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
Loop
Do While testcounter < 3
inputTestPoints = InputBox("Enter the points earned on test " & testcounter, "Grade Calculator", "0")
isconverted = Integer.TryParse(inputTestPoints, testpoints)
If isconverted Then
testcounter = testcounter + 1
totalpointsaccumulator = CInt(totalpointsaccumulator + testpoints)
Else
MessageBox.Show("Please enter a number.", "Grade calculator", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
Loop
' assign grade
Select Case totalpointsaccumulator
Case Is >= 360
grade = "A"
Case Is >= 320
grade = "B"
Case Is >= 280
grade = "C"
Case Is >= 240
grade = "D"
Case Else
grade = "F"
End Select
totalpointsLabel.Text = Convert.ToString(totalpointsaccumulator)
gradeLabel.Text = grade
End Sub
End Class
isconverted = Integer.TryParse(inputProjectPoints, CInt(projectpoints))
should be:
isconverted = Integer.TryParse(inputProjectPoints, projectpoints)
as well as:
Dim grade, projectpoints, testpoints As String
Should be:
Dim grade as String
Dim projectpoints, testpoints As Integer
You can't pass a reference variable as a different type by trying to convert/cast it, that just returns the value in the type you requested (if possible, which is ironic considering you're use of Integer.TryParse()) it doesn't actually change the underlying type of the variable you declared.
Because of this issue, your Integer.TryParse() always fails, meaning isconverted is always false and you'll always get the message box.
Edit: Forgot to add, Plutonix is right. Set Option Strict ON!!

Custom search from textbox switch/parameter

I think I am over engineering this a bit. Any assistance is greatly appreciated on how I can fix this little problem. I have an app that searches multiple sites. But if a user types a custom parameter of g=, then it will search google. The problem is I have right now is it strips the G from the first word of my search term. For example, If I type g=golf game, google pops up with olf game. With the other searches, the = character is getting stripped. Should I use contains instead of this custom firstChars function?
Here is my code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox1.Text = "" Then
MsgBox("Enter text to search on." & vbCrLf & Err.Description, MsgBoxStyle.Information, "Need search term to search on.")
TextBox1.Focus()
End If
Try
'CHECK FOR GOOGLE.COM SEARCHING
Dim MyString As String = TextBox1.Text
Dim MyChar() As Char = {"g", "G", "="}
Dim NewString As String = MyString.TrimStart(MyChar)
Dim myUri As New Uri("http://google.com/search?hl=en&q=" & NewString)
Dim first2Chars As String
Dim first3Chars As String
Dim first4Chars As String
first2Chars = TextBox1.Text.Substring(0, 2)
first3Chars = TextBox1.Text.Substring(0, 3)
first4Chars = TextBox1.Text.Substring(0, 4)
MsgBox(first2Chars)
If first2Chars = "G=" Or first2Chars = "g=" Then
System.Diagnostics.Process.Start(myUri.AbsoluteUri)
ElseIf first3Chars = "TS=" Or first3Chars = "ts=" Then
System.Diagnostics.Process.Start("https://localhost/search.do?query=" & Net.WebUtility.UrlEncode(TextBox1.Text))
ElseIf first4Chars = "PIC=" Or first4Chars = "pic=" Then
System.Diagnostics.Process.Start("https://localhost/search.do?query_pic=" & Net.WebUtility.UrlEncode(TextBox1.Text))
End If
Catch ex As Exception
MsgBox("Error running search. The error was: " & vbCrLf & Err.Description, MsgBoxStyle.Exclamation, "Error")
End Try
End Sub

Select from table Syntax with multiple paramaters

I need help with getting my syntax correct on the myDataAdapter.SelectCommand.CommandText line. I cannot seem to get the date to work as my second parameter, before it would show if a person was in a seat of my theatre, now I made more dates for shows so I need to check the seat and the date now and I cannot seem to get the date check to work:
Private Sub lblSeat1_MouseEnter(sender As Object, e As EventArgs) Handles lblSeat1.MouseEnter
'NEED HELP ON THIS LINE BELOW
myDataAdapter.SelectCommand.CommandText = ("select * from seating where seat_no = " & seatNumber(0) And "select * from seating where perf_date = " & lstPerfDates.SelectedIndex)
myDataSet.Clear()
myDataAdapter.Fill(myDataSet)
If myDataSet.Tables(0).Rows.Count = 0 Then
lblSeat1.BackColor = Color.Green
ToolTipSeats.SetToolTip(lblSeat1, "Available")
ElseIf myDataSet.Tables(0).Rows.Count = 1 Then
lblSeat1.BackColor = Color.Red
ToolTipSeats.SetToolTip(lblSeat1, myDataSet.Tables(0).Rows(0)("patron"))
End If
End Sub
Changed to use parameters, and missing .item before ("patron")
Private Sub lblSeat1_MouseEnter(sender As Object, e As EventArgs) Handles lblSeat1.MouseEnter
'NEED HELP ON THIS LINE BELOW
myDataAdapter.SelectCommand.CommandText = ("select * from seating where seat_no = #seatNumber and perf_date #perfDate")
myDataAdapter.SelectCommand.CommandType = CommandType.Text
myDataAdapter.SelectCommand.Parameters.AddWithValue("#seatNumber", seatNumber(0))
myDataAdapter.SelectCommand.Parameters.AddWithValue("#perfDate", lstPerfDates.SelectedValue)
myDataSet.Clear()
myDataAdapter.Fill(myDataSet)
If myDataSet.Tables(0).Rows.Count = 0 Then
lblSeat1.BackColor = Color.Green
ToolTipSeats.SetToolTip(lblSeat1, "Available")
ElseIf myDataSet.Tables(0).Rows.Count = 1 Then
lblSeat1.BackColor = Color.Red
ToolTipSeats.SetToolTip(lblSeat1, myDataSet.Tables(0).Rows(0).item("patron"))
End If
End Sub

How to keep user score in visual basic even if user failed validation first time?

Hello I am currently making an hangman game where you guess a randomly selected word and you have three rounds. Each time you win a round you gain 10 points, however if you don't guess the word before you run out of the 10 generous attempts. You will lose the round not gain anything.
After you win you three games of hangman, you are shown a new input text box in a high score form to input your name to save your high score to be displayed on the high score form and it has validation in (Meaning the user is required have at least one character inside the text box). This is where my main problem is, my input box will save your name and your points if you pass validation first time. However if you didn't pass validation first time but pass it the second time, your name is saved however your high score will be saved but only with one point. Sorry for my bad English, but is there anyway to keep the amount of points the user scores even if they failed validation first time instead of changing it to 1 point? Here is my code (Sorry for the bad indention):
Hangman Game Code (This is where the user gets their points from)
Imports System.IO
Public Class Hangman
'Public Variables
Public AttemptsLeft As Integer = 0
Public Rounds As Integer = 1
Public LetterChosen As Char
Dim EndWord() As Char
Dim AppPath As String = Application.StartupPath()
Dim FileRead() As String
Public GameWinner As Boolean = True
Dim HangmanShapes As New List(Of PowerPacks.Shape)
Public ScoreForRound As Integer
Dim NewControls As New List(Of Button)
Dim GameWord As New List(Of Label)
'Form Load code
Private Sub Hangman_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Load Word Game Code
If File.Exists(AppPath & "/wordlist.txt") Then
FileRead = IO.File.ReadAllLines(AppPath & "/wordlist.txt")
Dim RandomWord As New List(Of String)
For i = 0 To FileRead.Length - 1
RandomWord.Add(FileRead(i))
Next
Dim random As New Random() 'Using this to randomise each word
EndWord = RandomWord(random.Next(0, RandomWord.Count - 1)).ToUpper.ToCharArray 'Will put each character of the randomly chosen word into the labels.
Score.Text = UScore
Round.Text = Rounds
Letter1.Text = EndWord(0)
Letter1.Visible = False
Letter2.Text = EndWord(1)
Letter2.Visible = False
Letter3.Text = EndWord(2)
Letter3.Visible = False
Letter4.Text = EndWord(3)
Letter4.Visible = False
Letter5.Text = EndWord(4)
Letter5.Visible = False
Letter6.Text = EndWord(5)
Letter6.Visible = False
'Attempts left code
End If
With HangmanShapes
.Add(Attempt1)
.Add(Attempt2)
.Add(Attempt3)
.Add(Attempt4)
.Add(Attempt5)
.Add(Attempt6)
.Add(Attempt7)
.Add(Attempt8)
.Add(Attempt9)
.Add(Attempt10Part1)
.Add(Attempt10Part2)
End With
With NewControls
.Add(LetterA)
.Add(LetterB)
.Add(LetterC)
.Add(LetterD)
.Add(LetterE)
.Add(LetterF)
.Add(LetterG)
.Add(LetterH)
.Add(LetterI)
.Add(LetterJ)
.Add(LetterK)
.Add(LetterL)
.Add(LetterM)
.Add(LetterN)
.Add(LetterO)
.Add(LetterP)
.Add(LetterQ)
.Add(LetterR)
.Add(LetterS)
.Add(LetterT)
.Add(LetterU)
.Add(LetterV)
.Add(LetterW)
.Add(LetterX)
.Add(LetterY)
.Add(LetterZ)
End With
With GameWord
.Add(Me.Letter1)
.Add(Me.Letter2)
.Add(Me.Letter3)
.Add(Me.Letter4)
.Add(Me.Letter5)
.Add(Me.Letter6)
End With
End Sub
Private Sub AllBtnClicks(ByVal sender As System.Object, ByVal e As EventArgs) Handles LetterA.Click, LetterB.Click, LetterC.Click, LetterD.Click, LetterE.Click, LetterF.Click, LetterG.Click, LetterH.Click, LetterI.Click, LetterJ.Click, LetterK.Click, LetterL.Click, LetterM.Click, LetterN.Click, LetterO.Click, LetterP.Click, LetterQ.Click, LetterR.Click, LetterS.Click, LetterT.Click, LetterU.Click, LetterV.Click, LetterW.Click, LetterX.Click, LetterY.Click, LetterZ.Click
'Declartions
Dim LetterGuess As Button = sender
LetterGuess.Enabled = False
Dim LetterCorrect As Boolean = False
'Loop
For Each Letter In EndWord
If GetChar(LetterGuess.Name, 7) = Letter Then
Select Case Array.IndexOf(EndWord, Letter)
Case Is = 0
Letter1.Visible = True
Case Is = 1
Letter2.Visible = True
Case Is = 2
Letter3.Visible = True
Case Is = 3
Letter4.Visible = True
Case Is = 4
Letter5.Visible = True
Case Is = 5
Letter6.Visible = True
End Select
LetterCorrect = True
End If
Next
'Lives left code
If LetterCorrect = False Then
AttemptsLeft += 1
Select Case AttemptsLeft
Case 1
Attempt1.Visible = True
Attempts.Text = 1
Case 2
Attempt2.Visible = True
Attempts.Text = 2
Case 3
Attempt3.Visible = True
Attempts.Text = 3
Case 4
Attempt4.Visible = True
Attempts.Text = 4
Case 5
Attempt5.Visible = True
Attempts.Text = 5
Case 6
Attempt6.Visible = True
Attempts.Text = 6
Case 7
Attempt7.Visible = True
Attempts.Text = 7
Case 8
Attempt8.Visible = True
Attempts.Text = 8
Case 9
Attempt9.Visible = True
Attempts.Text = 9
Case 10
Attempt10Part1.Visible = True
Attempt10Part2.Visible = True
Attempts.Text = 10
LetterA.Enabled = False
LetterB.Enabled = False
LetterC.Enabled = False
LetterD.Enabled = False
LetterE.Enabled = False
LetterF.Enabled = False
LetterG.Enabled = False
LetterH.Enabled = False
LetterI.Enabled = False
LetterJ.Enabled = False
LetterK.Enabled = False
LetterL.Enabled = False
LetterM.Enabled = False
LetterN.Enabled = False
LetterO.Enabled = False
LetterP.Enabled = False
LetterQ.Enabled = False
LetterR.Enabled = False
LetterS.Enabled = False
LetterT.Enabled = False
LetterU.Enabled = False
LetterV.Enabled = False
LetterW.Enabled = False
LetterX.Enabled = False
LetterY.Enabled = False
LetterZ.Enabled = False
MsgBox("You have lost the round!")
ResetForm(0)
End Select
'Winning a round code
Else : Dim GameWinner As Boolean = True
Dim WordCheck As Label
For Each WordCheck In GameWord
If Not WordCheck.Visible Then
GameWinner = False
Exit For
End If
Next
If GameWinner Then
MsgBox("You have won the round!")
ResetForm(10)
'Losing a round code
End If
End If
End Sub
Private Sub ResetForm(ScoreForRound As Integer)
UScore += ScoreForRound
If Rounds = 3 Then
Me.Close()
HighScore.Show()
Else
Score.Text = +10
AttemptsLeft = 0
Attempts.Text = 0
Rounds += 1
Hangman_Load(Nothing, Nothing)
Dim HangmanReset As PowerPacks.Shape
For Each HangmanReset In HangmanShapes
HangmanReset.Visible = False
Next
Dim ControlReset As Control
For Each ControlReset In NewControls
ControlReset.Enabled = True
Next
End If
End Sub
End Class
High score form (This is where the user saves their points and also be able to view their high scores afterwards)
Imports System.IO
Public Class HighScore
Dim AppPath As String = Application.StartupPath()
Public Username As String
Private Sub HighScore_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim FileData() As String
Dim SizeArray As Integer
Try
FileData = File.ReadAllLines(AppPath & "/highscore.txt")
SizeArray = FileData.Length
Catch Break As Exception
MsgBox("The file is missing!", MsgBoxStyle.Critical)
End Try
For begin = 0 To SizeArray - 1 Step 1
Me.UserNameLabel.Text = UserNameLabel.Text & FileData(begin) & vbNewLine
Next
End Sub
Private Sub Backtomainmenu_Click(sender As Object, e As EventArgs) Handles Backtomainmenu.Click
MainMenu.Visible = True
Me.Visible = False
End Sub
Private Sub HelpButtonHighScore_Click(sender As Object, e As EventArgs) Handles HelpButtonHighScore.Click
MsgBox("This is the high score, this shows the top 10 players who achieved well in this game, this is ranked by the amount of points score. If you want to have your name in this high score, play the game well in order to achieve this.", MsgBoxStyle.Information)
End Sub
'This is where the user saves their high scores
Private Sub SaveName_Click(sender As Object, e As EventArgs) Handles SaveName.Click
Username = NameInput.Text
Try
File.WriteAllText(AppPath & "/highscore.txt", Username & " " & UScore)
Catch ex As Exception
MsgBox("The file is missing!", MsgBoxStyle.Critical)
End Try
UScore = vbNull
If NameInput.Text = "" Then
MsgBox("Enter a name please")
Else
File.WriteAllText(AppPath & "/highscore.txt", Username & " " & UScore)
Me.Close()
MainMenu.Show()
End If
End Sub
End Class
the user is required have at least one character inside the text box
Your code is currently saving to the file before any validation occurs:
Username = NameInput.Text
Try
File.WriteAllText(AppPath & "/highscore.txt", Username & " " & UScore)
Catch ex As Exception
MsgBox("The file is missing!", MsgBoxStyle.Critical)
End Try
UScore = vbNull
After that block of code (which has already written to the file), then you're attempting to validate:
If NameInput.Text = "" Then
MsgBox("Enter a name please")
Else
File.WriteAllText(AppPath & "/highscore.txt", Username & " " & UScore)
Me.Close()
MainMenu.Show()
End If
Consolidate the code, and only write to the file if your validation is successful:
Private Sub SaveName_Click(sender As Object, e As EventArgs) Handles SaveName.Click
Username = NameInput.Text.Trim
If Username = "" Then
MsgBox("Enter a name please!")
Else
Try
File.WriteAllText(AppPath & "/highscore.txt", Username & " " & UScore)
UScore = vbNull
Me.Close()
MainMenu.Show()
Catch ex As Exception
MsgBox("Error Saving High Score File!" & vbCrLf & vbCrLf & ex.ToString(), MsgBoxStyle.Critical)
End Try
End If
End Sub
With UScore = vbNull, you might be resetting the score even if NameInput.Text = "".
So, instead of
Try
File.WriteAllText(AppPath & "/highscore.txt", Username & " " & UScore)
Catch ex As Exception
MsgBox("The file is missing!", MsgBoxStyle.Critical)
End Try
UScore = vbNull
If NameInput.Text = "" Then
MsgBox("Enter a name please")
Else
File.WriteAllText(AppPath & "/highscore.txt", Username & " " & UScore)
Me.Close()
MainMenu.Show()
End If
Put UScore = vbNull inside the If statement so
Try
File.WriteAllText(AppPath & "/highscore.txt", Username & " " & UScore)
Catch ex As Exception
MsgBox("The file is missing!", MsgBoxStyle.Critical)
End Try
If NameInput.Text = "" Then
MsgBox("Enter a name please")
Else
File.WriteAllText(AppPath & "/highscore.txt", Username & " " & UScore)
Me.Close()
MainMenu.Show()
UScore = vbNull 'Put it here instead
End If

Error Handling: Cannot place Try...catch inside if...then

My current assignment has me using a try and catch block for error handling. The code is supposed to calculate values for going over 500 to input a certain value and under 500 a different value. My problem is I don't know where to put the try and catch handling lines. If I put the try above the if statement and catch statements after dueLbl.Text = "your payment is " & FormatCurrency(totalDue)
I receive endif must match if,else must precede if, and catch never reached. Now if I leave the try above the if statement and leave the catch at the very bottom the code will run but still wont catch anything.
Public Class Form1
Private Sub calcButton_Click(sender As Object, e As EventArgs) Handles calcButton.Click
Dim kwHour As Double
Dim totalDue As Double
Dim basePay As Double
Dim overBasePay As Double
kwHour = kwhourValue.Text
If kwHour <= 500 Then
totalDue = kwHour * 0.27
dueLbl.Text = "your payment is " & FormatCurrency(totalDue)
Else
basePay = 500 * 0.27
overBasePay = (kwHour - 500) * 0.55
totalDue = basePay + overBasePay
dueLbl.Text = "your payment is " & FormatCurrency(totalDue)
End If
End Sub
End Class
You can just do it like this...
Private Sub calcButton_Click(sender As Object, e As EventArgs) Handles calcButton.Click
Try
Dim kwHour As Double
Dim totalDue As Double
Dim basePay As Double
Dim overBasePay As Double
kwHour = kwhourValue.Text
If kwHour <= 500 Then
totalDue = kwHour * 0.27
dueLbl.Text = "your payment is " & FormatCurrency(totalDue)
Else
basePay = 500 * 0.27
overBasePay = (kwHour - 500) * 0.55
totalDue = basePay + overBasePay
dueLbl.Text = "your payment is " & FormatCurrency(totalDue)
End If
Catch ex as Exception
MsgBox(ex.message)
Finally
'Whatever you want to do...
End Try
End Sub
You can't place the Try Catch statement in the middle of an IF statement. That won't end your IF statement properly. The code above will catch whatever error it meets along executing your code. Additionally, you can add Finally. Whatever code under this will get executed after it meets the error or not. Kind of like a finale code :)
When you say
Now if I leave the try above the if statement and leave the catch at the very bottom the code will run but still wont catch anything.
I'm guessing you are getting the error in
kwHour = kwhourValue.Text
So what you can do is put the try statement before that line wrapping that line also in the try catch block. I'm assuming here that you are asked specifically to use try catch blocks only. Otherwise there are other ways to do things here. What does your assignment say exactly?
In this way... BTW you need to convert kwhourValue.Text to Double
Private Sub calcButton_Click(sender As Object, e As EventArgs) Handles calcButton.Click
Dim kwHour As Double
Dim totalDue As Double
Dim basePay As Double
Dim overBasePay As Double
Try
If Double.TryParse(kwhourValue.Text, kwHour) Then
' text is convertible to Double, and kwHour contains the Double value now
Else
' Cannot convert text to Double
End Sub
End If
If kwHour <= 500 Then
totalDue = kwHour * 0.27
dueLbl.Text = "your payment is " & FormatCurrency(totalDue)
Else
basePay = 500 * 0.27
overBasePay = (kwHour - 500) * 0.55
totalDue = basePay + overBasePay
dueLbl.Text = "your payment is " & FormatCurrency(totalDue)
End If
Catch ex as Exception
MsgBox(ex.message)
Finally
'Whatever you want to do...
End Try
End Sub