VB.NET - Accumulating Numbers and Calculating Average - vb.net

I have started over and everything is working as intended except for 2 of the accumulating totals, the calculation is not working the way I need it to. Instead of adding previous sales to the total it tacks the new sale on the end...
for example: I input 1 Snowboard and 1 Snowboard with Boots, this works, 1 is shown in the summary for both Snowboards and Snowboards with Boots. However when I try to input again in order to keep a running total of sales I have a problem, I enter 1 Snowboard and 1 Snowboard with Boots, and the summaries show 11 rather than 2. Why does this happen?
' Declare module-level variables and constants.
Private SnowBoardsSold, BootsSold, SaleCount As Integer
Private ItemsSold As Integer
Private TotalSales As Decimal
Const SNOWBOARD_RATE As Decimal = 20D
Const BOOTS_RATE As Decimal = 30D
Private Sub CalculateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CalculateButton.Click
' Calculate the prices
Dim SnowBoards, Boots As Integer
Dim SnowBoardSale, BootsSale, ThisSale, AverageSalesEver As Decimal
Try
' Convert the Snowboard input to numeric variable.
SnowBoards = Integer.Parse(SnowboardsTextBox.Text)
Try
' Convert Boots if Snowboard was successful.
Boots = Integer.Parse(WithBootsTextBox.Text)
' Calculate values for sale.
SnowBoardSale = SnowBoards * SNOWBOARD_RATE
BootsSale = Boots * BOOTS_RATE
ThisSale = SnowBoardSale + BootsSale
' Calculate summary values.
TotalSales += ThisSale
BootsSold += BootsSale
SnowBoardsSold += SnowBoardSale
SaleCount += 1
AverageSalesEver = TotalSales / SaleCount
' Format and display prices for the sale.
SnowBoardsPriceTextBox.Text = SnowBoardSale.ToString("c")
BootsPriceTextBox.Text = BootsSale.ToString("c")
TotalPriceTextBox.Text = ThisSale.ToString("c")
' Format and display values for the summary.
SnowBoardRentalTextBox.Text += SnowBoards.ToString()
BootsRentalTextBox.Text += Boots.ToString()
TotalChargesTextBox.Text = TotalSales.ToString("c")
AverageChargeTextBox.Text = AverageSalesEver.ToString("c")
Catch BootsException As FormatException
' Handle a Boots exception.
MessageBox.Show("Please enter numbers.", "Data Entry Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
With WithBootsTextBox
.Focus()
.SelectAll()
End With
End Try
Catch SnowBoardsException As FormatException
' Handle a SnowBoard exception.
MessageBox.Show("Please enter numbers.", "Data Entry Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
With SnowboardsTextBox
.Focus()
.SelectAll()
End With
Catch AnException As Exception
'Handle any other exception.
MessageBox.Show("Error: " & AnException.Message)
End Try
End Sub

First, you might want to change the way you grab the numbers:
'Convert snowboard input value to numeric variable.
SnowboardInteger = Integer.Parse(SnowboardsTextBox.Text)
to:
Dim SnowboardInteger As Integer
If TryParse.Integer(SnowboardsTextBox.Text, SnowboardInteger) = False then
' if it parses, SnowboardInteger will have the value,
'else the function returns false
MessageBox.Show("Please enter numbers")
End if
Also, you are parsing the textboxes twice. Once in the declaration then right after. This doesnt look right:
SnowboardSaleCountInteger += 1
WithBootsSaleCountInteger += 1
TotalSaleCountInteger += TotalChargesSumInteger ' ?????
AverageChargeInteger = TotalChargesSumInteger / TotalSaleCountInteger
Adding 'charges' to a 'counter' doesnt seem right. If you want the avg shouldnt it be:
TotalSaleCountInteger = SnowboardSaleCountInteger + WithBootsSaleCountInteger
If you want fractions such as 'xx.yy' in the result, AverageChargeInteger should be a Double or Decimal, unless whole dollars are ok for the assignment.
If you need to accumulate from previous clicks, then you need to move some declarations out of the procedure up by SnowboardSumInteger, WithBootsSumInteger so they can accumulate. As it is, WithBootsSaleCountInteger, TotalSaleCountInteger dont do anything and are always 1. I wonder if as a 'SaleCounter' they shouldnt increase by the value in the textbox rather than just 1 (dont have the assignment in front of me).
One more thing you might need to do is here:
SnowboardPriceInteger = SnowboardInteger * SNOWBOARD_RENTAL_RATE
WithBootsPriceInteger = WithBootsInteger * WITH_BOOTS_RENTAL_RATE
TotalPriceInteger = SnowboardPriceInteger + WithBootsPriceInteger
Your constants are Decimal (SNOWBOARD_RENTAL_RATE) so, the result of the calc has to go into a Decimal var, but SnowboardPriceInteger and the other are not. An integer cannot store a fractional result from the multiplication or division.
something like:
' sales accumulators
Private TotalSales As Decimal = 0
Private ItemsSold As Integer = 0
Click Event:
' this sale:
Dim Snowboards As Integer
Dim Boots As Integer
' get the values from the text boxes, then:
Dim SnowBoardSale As Decimal = (SnowBoards * SnowBoardRate)
Dim BootsSale As Decimal = (Boots * BootsRate)
Dim ThisSale As Decimal = SnowBoardSale + BootsSale
' update accumulators
TotalSales += ThisSale
ItemsSold += (Boots + Snowboards)
' calc the average
Dim AverageSalesEver AS Decimal = TotalSales / ItemsSold
' Display results in textboxes
'(this exercise is left to the student ;) )
HTH
I think you just confused yourself with too many variables and ones left over from old attempts.

Related

Invalid Conversion - Cast Exception: 'System.InvalidCastException'

I have written a code that works perfectly as long as the user enters the information in correctly. If the user does enter a number in the text box, I have an error message that tells the user data must be entered. When this happens I am getting a cast exception:
Exception thrown: 'System.InvalidCastException' in Microsoft.VisualBasic.dll
Additional information: Conversion from string "" to type 'Integer' is not valid.
I am new to this and I would appreciate any suggestions.
The exception occurs on this line:
intDetermineSubTotalCost(intSiteSelected, CInt(txtNumberOfNights.Text))
If I remove the option strict on, it will work with expected conversation, however the project requires it to be on.
Dim intSiteSelected As Double
Dim intNumberOfNights As Integer
Dim blnNightsStayingIsVaild As Boolean = False
Dim blnDiscountIsSelected As Boolean = False
Dim intDiscountChoice As Integer
Dim strDiscountSelected As String = ""
' Call a function to confirm if the Number of Nights staying is valid.
blnNightsStayingIsVaild = ValidateNightsStaying()
' call a function to confirm a discount has been seected.
intDiscountChoice = ValidateSelectedDiscount(blnDiscountIsSelected, strDiscountSelected)
' If number of nights staying and available discount has been selected,
' calculate the subtotal, tax, and final cost.
If (blnNightsStayingIsVaild And blnDiscountIsSelected) Then
intNumberOfNights = Convert.ToInt32(txtNumberOfNights.Text)
intSiteSelected = Me.cmbSelectASite.SelectedIndex
End If
If cmbSelectASite.SelectedIndex = 0 Then
intSiteSelected = 20D
ElseIf cmbSelectASite.SelectedIndex = 1 Then
intSiteSelected = 35D
ElseIf cmbSelectASite.SelectedIndex = 2 Then
intSiteSelected = 55D
End If
intDetermineSubTotalCost(intSiteSelected, CInt(txtNumberOfNights.Text))
Private Function ValidateNightsStaying() As Boolean
' This function validate the value entered for the number of nights staying in campground.
Dim intNightsStaying As Integer
Dim blnValidityCheck As Boolean = False
Dim StrNumberOfNightsErrorMessage As String =
"Please Enter The Number Of Nights You Are Staying (1-99)"
Dim strMessageBoxTitle As String = " You Must Choose Number Of Nights"
Try
intNightsStaying = Convert.ToInt32(txtNumberOfNights.Text)
If intNightsStaying > 0 And intNightsStaying < 100 Then
blnValidityCheck = True
Else
MsgBox(StrNumberOfNightsErrorMessage, , strMessageBoxTitle)
blnValidityCheck = True
End If
Catch Exception As FormatException
MsgBox(StrNumberOfNightsErrorMessage, , strMessageBoxTitle)
txtNumberOfNights.Focus()
txtNumberOfNights.Clear()
Catch execption As OverflowException
MsgBox(StrNumberOfNightsErrorMessage, , strMessageBoxTitle)
txtNumberOfNights.Focus()
txtNumberOfNights.Clear()
Catch execption As SystemException
MsgBox(StrNumberOfNightsErrorMessage, , strMessageBoxTitle)
txtNumberOfNights.Focus()
txtNumberOfNights.Clear()
End Try
Return blnValidityCheck
End Function
You could look at something like this that would restrict them from entering non-numeric keypresses.
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
'97 - 122 = Ascii codes for simple letters
'65 - 90 = Ascii codes for capital letters
'48 - 57 = Ascii codes for numbers
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
e.Handled = True
End If
End If
End Sub
Just Do some input checking before your perform you calculations.
For Example A Textbox requiring Input:
If txtInput.text.Contains("whatever you don't want there") Then
MessageBox.Show("Please Enter The Correct Info")
txtInput.Focus()
Return
End if
Or
If Integer.TryParse(txtInput.Text, input) Then
MessageBox.Show("Please Enter Some Text.")
txtInput.Focus()
Return
End If
This Stops the code crashing if there is an error and gives the user the opportunity to fix their input. Once all the input has been checked, perform your calculations.
There are a few ways to solve this.
You could check that the string is not empty and validate on that.
Change the conversion to a TryParse which IIRC will return 0 on empty
If possible, change the input from a textbox to a numeric up/down control with min and max values of 1 and 99 respectively.
Change your TextBox to a Masked TextBox. Allow only numbers in the mask.
https://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox%28v=vs.110%29.aspx

Visual Basic code- Having trouble displaying the Total. New to VB

I have to write a program that calculates costs for a catering company. i have that part down, but whats stumping me is I have trouble displaying the total. What also is stumping me is that i have to make a summary button that adds everything up into a grand total from the previous calculations and display it in a message box. displaying and calculations aren't really my issues, but getting the data to calculate is.
Thank you
HERE's the code.
Const decPRIME_RIB As Decimal = 25.95D
Const decCHICKEN As Decimal = 18.95D
Const decPASTA As Decimal = 12.95D
Const decOPEN_BAR As Decimal = 25D
Const decWINE As Decimal = 8D
Const decBEER As Decimal = 10D
'Declare module-level variables for summary information.
Private TotalDollar As Decimal
Private AmountDue As Decimal
Private SubTotalDecimal As Decimal
Private TotalDecimal As Decimal
Private Guest As Integer
Private EventCountInteger As Integer
Private Sub CalcBtn_Click(sender As Object, e As EventArgs) Handles CalcBtn.Click
' Calculate and display the current amounts and add to totals.
Dim FoodChoiceDecimal As Decimal
Dim OpenBarDecimal As Decimal
Dim WineDecimal As Decimal
Dim DrinksDecimal As Decimal
' Find the price.
If PrimeRB.Checked Then
FoodChoiceDecimal = decPRIME_RIB
ElseIf ChickRB.Checked Then
FoodChoiceDecimal = decCHICKEN
ElseIf PastaRB.Checked Then
FoodChoiceDecimal = decPASTA
End If
If OpenCB.Checked Then
OpenBarDecimal = decOPEN_BAR
End If
If WineCB.Checked Then
WineDecimal = decWINE
End If
'Multiply price by number of guest and drink selection.
Try
DrinksDecimal = (OpenBarDecimal + WineDecimal)
AmountDue = (FoodChoiceDecimal + DrinksDecimal) * Guest
' display totals.
TotalLbl.Text = TotalLbl.ToString("C")
' Allow change for new event.
OpenCB.Enabled = False
WineCB.Enabled = False
ClearBtn.Enabled = True
SummaryBtn.Enabled = True
Catch NumberOfGuestsException As FormatException
MessageBox.Show("Number of Guests must be Numeric", _
"Data entry Error", MessageBoxButtons.OK, _
MessageBoxIcon.Information)
End Try
End Sub
Private Sub SummaryBtn_Click(sender As Object, e As EventArgs) Handles SummaryBtn.Click
' Calculate total dollar amounts and number of events.
Dim MessageString As String
If EventCountInteger > 0 Then
' Calculate the summary sales totals.
TotalDollar += AmountDue
'Concatenate the message string.
MessageString = "Number of Events:" & EventCountInteger.ToString() _
& Environment.NewLine & Environment.NewLine _
& "Total Sales: " & TotalDollar.ToString("C")
MessageBox.Show(MessageString, "Sales Summary", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
End If

find average of variables

Full disclosure, I'm working on an assignment for COP2170, but the additional feature isn't apart of the assignment just trying to stretch a little further...
I'm trying to add 5 test scores and output the average of the 5 scores, that part works just fine. In addition I'm trying to add an additional feature that will allow the user to enter less than 5 scores and the program will still output the average of whatever scores were entered.
So this works:
And this works:
The problem I'm running into is if the first score is omitted and the rest are filled in, it doesn't work:
Here's the code I've got so far:
Public Class frmTestScoreAverage
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim decScore1, decScore2, decScore3, decScore4, decScore5 As Double ' decScore1-5 to hold test scores1-5
Dim decScoreAverage As Double ' to hold test score average
Dim intDivideBy As Double = 5 ' declare intDivideBy variable with starting value of 5
lblStatusLabel.Text = String.Empty 'set error message to empty string
Try
' Read user input convert to double and assign value to variable
decScore1 = Convert.ToDouble(txtScore1.Text)
decScore2 = Convert.ToDouble(txtScore2.Text)
decScore3 = Convert.ToDouble(txtScore3.Text)
decScore4 = Convert.ToDouble(txtScore4.Text)
decScore5 = Convert.ToDouble(txtScore5.Text)
' Calculate average
decScoreAverage = (decScore1 + decScore2 + decScore3 + decScore4 + decScore5) / intDivideBy
'display result
lblResult.Text = CStr(decScoreAverage)
Catch
' Display error message, asks for all scores
lblStatusLabel.Text = "Please enter all test scores"
'Calculate average even without all scores
For Each c As TextBox In Me.Controls.OfType(Of TextBox)() 'loop through each textbox in form see: http://stackoverflow.com/a/13504361/1947286
If c.Text = String.Empty Then intDivideBy -= 1 'If text equals empty string, Then decrement intDivideBy
Next
'catch divide by zero error
Try
'calculate average
decScoreAverage = (decScore1 + decScore2 + decScore3 + decScore4 + decScore5) / intDivideBy 'add test scores and divide to find average
'display result
lblResult.Text = CStr(decScoreAverage)
Catch
lblStatusLabel.Text = "Please enter at least one test score"
End Try
End Try
End Sub
End Class
I'm pretty sure the problem has to do with the way I'm finding the average:
decScoreAverage = (decScore1 + decScore2 + decScore3 + decScore4 + decScore5) / intDivideBy
Is there a way to find the average that will allow for empty variables in any arrangement?
The problem you are having is that Convert.ToDouble(txtBox.text) (with empty string, will make Convert throw an Exception.
Add a validation that the string isn't empty or use TryParse to see if the Textbox value is parseable to a number.
Either
If not String.IsNullOrEmpty(txtBox.Text) then
Convert.ToDouble(txtBox.text)
Or
dim value as Double
if Double.TryParse(txtBox.Text, value) then
avg += value
When the first one is empty, it goes to the Catch part of the code, then you try to calculate the avg, but the values of the Txtbox are not assigned to the declarations you made, so when it tries to do the average
decScore1 = Convert.ToDouble(txtScore1.Text) // Exception here to Catch
decScore2 = Convert.ToDouble(txtScore2.Text) // Not evaluated
decScore3 = Convert.ToDouble(txtScore3.Text) // Not evaluated
decScore4 = Convert.ToDouble(txtScore4.Text) // Not evaluated
decScore5 = Convert.ToDouble(txtScore5.Text) // Not evaluated
Theses do not have any value, in return this doesn't do what you want
decScoreAverage = (decScore1 + decScore2 + decScore3 + decScore4 + decScore5) / intDivideBy
UPDATE
(Vb code not tested)
Function GetTextValue(dim score as string) as Double
dim value as Double = 0
if (Double.TryParse(score, value))
return value
else
return value
End Function
This
decScore1 = Convert.ToDouble(txtScore1.Text)
Becomes
decScore1 = GetTextValue(txtScore1.Text)
I suggest you store reference to each textbox in an array. You'll see why at the end of this example.
Public Class frmTestScoreAverage
Public Sub New()
Me.InitializeComponent()
Me.boxes = {Me.txtScore1, Me.txtScore2, Me.txtScore3, Me.txtScore4, Me.txtScore5}
End Sub
Private boxes As TextBox()
The common way to validate user input in winforms is to handle the Validating event, usually combined with the error provider class as mentioned by Hans Passant.
Private Sub HandleScoreValidating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles txtScore1.Validating, txtScore2.Validating, txtScore3.Validating, txtScore4.Validating, txtScore5.Validating
With DirectCast(sender, TextBox)
If ((Not String.IsNullOrEmpty(.Text)) AndAlso (Not Double.TryParse(.Text, 0.0R))) Then
e.Cancel = True
'Alert or set error provider:
'Me.ErrorProvider1.SetError(DirectCast(sender, Control), "Not double")
Else
e.Cancel = False
'Clear error provider:
'Me.ErrorProvider1.Clear()
End If
End With
End Sub
Now, back to the textbox array. Create a new list of double and iterate the textbox array. If the text isn't empty, parse and add the value to the list. At the end, use the Average extension method to get the average value.
Private Sub HandleCalculate(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim values As New List(Of Double)
For Each box As TextBox In Me.boxes
If (Not String.IsNullOrEmpty(box.Text)) Then
values.Add(Double.Parse(box.Text))
'Else
' values.Add(0.0R)
End If
Next
Dim average As Double = values.Average()
'....
End Sub
End Class

Variable won't change

I'm trying to finish a project for class that calculates the occupancy rate of a hotel using an InputBox object. However, the variables are getting permanently set as the first value entered.
Allow me to clarify what is happening. I click the button to bring up the InputBox I enter a number e.g. 10, then I click ok, then I enter a new number for the second one e.g. 7, but the list box displays both as the first one. Once I enter all the numbers for the Rooms Sold I then continue to enter the values for Rooms Available, but the number form the first loop somehow carried over to the second one and WILL NOT change.
What can I do to make it so the variable is reset for each iteration of the loop. I have it set the variable back to 0 after it has added itself to the total and the list, but it won't change.
And i did do research. The MSDN knowledge base was no help, I could only find one question on here like this and he just forgot to define a string, and I tried Google but to no avail.
Here is my code:
Public Class frmOccupancyRateCalculator
Private Sub frmOccupancyRateCalculator_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lstRoomsSold.Items.Clear()
lstRoomsAvailable.Items.Clear()
End Sub
Private Sub btnEnterRoomSales_Click(sender As Object, e As EventArgs) Handles btnEnterRoomSales.Click
' Declare the arithimetic and message variables.
Dim intRoomsSold As Integer
Dim intRoomsAvailable As Integer
Dim intTotalRooms As Integer
Dim intTotalRoomsSold As Integer
Dim intTotalRoomsAvailable As Integer
Dim intRoomsSoldNumberOfEntries As Integer = 1
Dim intRoomsAvailableNumberOfEntries As Integer = 1
Dim intNumberOfEntries As Integer = 1
Dim intMaxNumberOfEntries As Integer = 7
Dim decOccupancyRate As Decimal
Dim strRoomsSold As String
Dim strRoomsSoldInputMessage As String = "Enter the number of rooms sold for floor #"
Dim strRoomsSoldInputHeading As String = "Enter Rooms Sold"
Dim strRoomsSoldNormalMessage As String = "Enter the number of rooms sold for floor #"
Dim strRoomsSoldNonNumericError As String = "Error - Non-Numeric value entered. Please enter a whole number of rooms sold for floor #"
Dim strRoomsSoldNegativeError As String = "Error - Negative number entered. Please enter a whole number greater than zero of rooms sold for floor #"
Dim strRoomsSoldDecimalError As String = "Error - Decimal number entered. Plerase enter a whole number of rooms sold for floor #"
Dim strRoomsAvailable As String
Dim strRoomsAvailableInputMessage As String = "Enter the number of rooms available for floor #"
Dim strRoomsAvailableInputHeading As String = "Enter Rooms Available"
Dim strRoomsAvailableNormalMessage As String = "Enter the number of rooms available for floor #"
Dim strRoomsAvailableNonNumericError As String = "Error - Non-Numeric value entered. Please enter a whole number of rooms available for floor #"
Dim strRoomsAvailableNegativeError As String = "Error - Negative number entered. Please enter a whole number greater than zero of rooms available for floor #"
Dim strRoomsAvailableDecimalError As String = "Error - Decimal number entered. Plerase enter a whole number of rooms available for floor #"
Dim strCancelClicked As String = ""
' Define the RoomsSoldInputMessage variables
strRoomsSold = InputBox(strRoomsSoldInputMessage & intRoomsSoldNumberOfEntries, strRoomsSoldInputHeading, " ")
' Loop to iterate until hours of travel are entered for all days of travel
Do Until intRoomsSoldNumberOfEntries > intMaxNumberOfEntries
' Is the input numeric?
If IsNumeric(strRoomsSold) Then
intRoomsSold = Convert.ToDecimal(strRoomsSold)
' Is the input greater or equal to 0?
If intRoomsSold >= 0 Then
' Is the number of rooms sold a whole number?
'If intRoomsSold Mod 1 = 0 Then
intTotalRoomsSold += intRoomsSold
lstRoomsSold.Items.Add(intRoomsSold)
intRoomsSoldNumberOfEntries += 1
intRoomsSold = 0
strRoomsSoldInputMessage = strRoomsSoldNormalMessage
' Display decimal error message
'Else
'strRoomsSoldInputMessage = strRoomsSoldDecimalError
'End If
' Display negative number error message
Else
strRoomsSoldInputMessage = strRoomsSoldNegativeError
End If
' Display non-numeric error message
Else
strRoomsSoldInputMessage = strRoomsSoldNonNumericError
End If
' Is the number of entries less than or equal to the maximum?
If intRoomsSoldNumberOfEntries <= intMaxNumberOfEntries Then
strRoomsSoldInputMessage = InputBox(strRoomsSoldInputMessage & intRoomsSoldNumberOfEntries, strRoomsSoldInputHeading, " ")
End If
Loop
' Define the RoomsAvailableInputMessage variable
strRoomsAvailable = InputBox(strRoomsAvailableInputMessage & intRoomsAvailableNumberOfEntries, strRoomsAvailableInputHeading, " ")
Do Until intRoomsAvailableNumberOfEntries > intMaxNumberOfEntries
' Is the input numeric?
If IsNumeric(strRoomsAvailable) Then
intRoomsAvailable = Convert.ToDecimal(strRoomsAvailable)
' Is the input greater or equal to 0?
If intRoomsAvailable >= 0 Then
' Is the number of rooms sold a whole number?
'If intRoomsAvailable Mod 1 = 0 Then
intTotalRoomsAvailable += intRoomsAvailable
lstRoomsAvailable.Items.Add(intRoomsAvailable)
intRoomsAvailableNumberOfEntries += 1
intRoomsAvailable = 0
strRoomsAvailableInputMessage = strRoomsAvailableNormalMessage
' Is the number of entries equal to the maximum number of entries?
If intRoomsAvailableNumberOfEntries = intMaxNumberOfEntries Then
intNumberOfEntries += 1
End If
' Display decimal error message
'Else
' strRoomsAvailableInputMessage = strRoomsAvailableDecimalError
' End If
' Display negative number error message
Else
strRoomsAvailableInputMessage = strRoomsAvailableNegativeError
End If
' Display non-numeric error message
Else
strRoomsAvailableInputMessage = strRoomsAvailableNonNumericError
End If
' Is the number of entries less than or equal to the maximum?
If intRoomsAvailableNumberOfEntries <= intMaxNumberOfEntries Then
strRoomsAvailableInputMessage = InputBox(strRoomsAvailableInputMessage & intRoomsAvailableNumberOfEntries, strRoomsAvailableInputHeading, " ")
End If
Loop
' Is the number of rooms sold entries greater than 1?
If intNumberOfEntries > 1 Then
' Display result label and totals
intTotalRooms = intTotalRoomsSold + intTotalRoomsAvailable
decOccupancyRate = intTotalRoomsSold / intTotalRooms
lblResult.Visible = True
lblResult.Text = intTotalRooms & vbNewLine & intTotalRoomsSold & vbNewLine & intTotalRoomsAvailable & vbNewLine & vbNewLine & decOccupancyRate.ToString("P")
' Disable the Enter Room Sales button
btnEnterRoomSales.Enabled = False
' Display error message for no values entered
Else
MsgBox("No Rooms Sold/Available value entered")
End If
End Sub
Private Sub mnuClear_Click(sender As Object, e As EventArgs) Handles mnuClear.Click
' This script is executed when the user taps or clicks the Clear menu item.
' It clears the Room Sales and Rooms Available ListBoxes, hides the Result label,
' enables the Enter Room Sales button.
lstRoomsSold.Items.Clear()
lstRoomsAvailable.Items.Clear()
lblResult.Visible = False
btnEnterRoomSales.Enabled = True
End Sub
Private Sub mnuExit_Click(sender As Object, e As EventArgs) Handles mnuExit.Click
' This script is executed when the user taps or clicks the Exit menu item.
' The window is closed and the program is terminated.
Close()
End Sub
End Class
Ok I figured it out. I needed to put the strRoomsSold and strRoomsAvailable variable definitions within the loops, then remove the second sequence within the Do Until loop.
' Loop to iterate until Rooms Sold number of Entries is greater than the maximum
Do Until intRoomsSoldNumberOfEntries > intMaxNumberOfEntries
' Define the RoomsSold variable
strRoomsSold = InputBox(strRoomsSoldInputMessage & intRoomsSoldNumberOfEntries, strRoomsSoldInputHeading, " ")
If strRoomsSold = strCancelClicked Then
strRoomsSoldInputMessage = strRoomsAvailableBlankError
Else
' Is the input numeric?
If IsNumeric(strRoomsSold) Then
intRoomsSold = Convert.ToDecimal(strRoomsSold)
' Is the input greater or equal to 0?
If intRoomsSold >= 0 Then
' Is the number of rooms sold a whole number?
If intRoomsSold Mod 1 = 0 Then
intTotalRoomsSold += intRoomsSold
lstRoomsSold.Items.Add(intRoomsSold)
intRoomsSoldNumberOfEntries += 1
strRoomsSoldInputMessage = strRoomsSoldNormalMessage
' Display decimal error message
Else
strRoomsSoldInputMessage = strRoomsSoldDecimalError
End If
' Display negative number error message
Else
strRoomsSoldInputMessage = strRoomsSoldNegativeError
End If
' Display non-numeric error message
Else
strRoomsSoldInputMessage = strRoomsSoldNonNumericError
End If
End If
Loop
Do Until intRoomsAvailableNumberOfEntries > intMaxNumberOfEntries
' Define the RoomsAvailable variable
strRoomsAvailable = InputBox(strRoomsAvailableInputMessage & intRoomsAvailableNumberOfEntries, strRoomsAvailableInputHeading, " ")
' Is the input numeric?
If IsNumeric(strRoomsAvailable) Then
intRoomsAvailable = Convert.ToDecimal(strRoomsAvailable)
' Is the input greater or equal to 0?
If intRoomsAvailable >= 0 Then
' Is the number of rooms sold a whole number?
If intRoomsAvailable Mod 1 = 0 Then
intTotalRoomsAvailable += intRoomsAvailable
lstRoomsAvailable.Items.Add(intRoomsAvailable)
intRoomsAvailableNumberOfEntries += 1
strRoomsAvailableInputMessage = strRoomsAvailableNormalMessage
' Is the number of entries equal to the maximum number of entries?
If intRoomsAvailableNumberOfEntries = intMaxNumberOfEntries Then
intNumberOfEntries += 1
End If
' Display decimal error message
Else
strRoomsAvailableInputMessage = strRoomsAvailableDecimalError
End If
' Display negative number error message
Else
strRoomsAvailableInputMessage = strRoomsAvailableNegativeError
End If
' Display non-numeric error message
Else
strRoomsAvailableInputMessage = strRoomsAvailableNonNumericError
End If
Loop

VB.net: Input string not correct format?

Hey guys I have been having this crashing problem with my program.
I am trying to create a program where it calculates a persons account balance by inputting their beginning balance, credit limit, total charges, and total credits. In this case I am having specific problems with the Total Charges and Total Credits Code.
I have a message box set up to where if the Total Charges and total credits box are blank it will say "please enter a numeric value for ....". The problem is that when I do run it and enter a blank, the message shows up and then the program crashes.
After crashing, the The program then highlights in yellow the specific conversion code (in this case: decTotalCharges = Convert.ToDecimal(txtTotalCharges.Text)) and the error says Input string was not in correct format.
What's going on, I converted it into a correct format right? (decimal to decimal?). Here's an in depth look at my code:
Public Class frmEndingBalance
'Declare module level variables
Dim mdecEndingBalance As Decimal
Dim mdecAllCharges As Decimal
Dim mdecAllCredits As Decimal
Dim mintCustomersOverLimit As Integer
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
'clears the form
'clears the labels
txtAccountNumber.Text = ""
txtBeginningBalance.Text = ""
txtTotalCharges.Text = ""
txtTotalCredits.Text = ""
txtCreditLimit.Text = ""
lblEndingBalance.Text = ""
lblCreditMessage.Text = ""
lblAllCharges.Text = ""
lblAllCredits.Text = ""
lblCustomersOverLimit.Text = ""
lblCreditMessage.Text = ""
'clear the textboxes
txtAccountNumber.Clear()
txtBeginningBalance.Clear()
txtTotalCredits.Clear()
txtTotalCharges.Clear()
txtCreditLimit.Clear()
'clear module level variables
mdecEndingBalance = 0
mdecAllCharges = 0
mdecAllCredits = 0
mintCustomersOverLimit = 0
End Sub
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
'Declare Variables
Dim intAccountNumber As Integer
Dim intBeginningBalance As Integer
Dim decTotalCharges As Decimal
Dim decTotalCredits As Decimal
Dim decCreditLimit As Decimal
Dim mdecEndingBalance As Decimal 'Beginning Balance + Charges - Credits()
Dim decCreditMessage As Decimal
'check for numeric
If IsNumeric(txtAccountNumber.Text) = False Then 'value is not numeric
MessageBox.Show("You can't enter anything blank!")
Exit Sub
End If
'convert to a numeric data type
intAccountNumber = Convert.ToInt32(txtAccountNumber.Text)
'check for numeric
If String.IsNullOrEmpty(txtBeginningBalance.Text) Then MessageBox.Show("Beginning Balance Cannot Be Blank!")
'check for everything else
If IsNumeric(txtBeginningBalance.Text) = False Then 'Value is not numeric
MessageBox.Show("Please enter a numeric value for Beginning Balance!")
Exit Sub
End If
'convert to a numeric data type
intBeginningBalance = Convert.ToInt32(txtBeginningBalance.Text)
'check for numeric
If IsNumeric(txtTotalCharges.Text) = False Then 'value is not numeric
MessageBox.Show("Please enter a numeric value for Total Charges!")
End If
'convert
decTotalCharges = Convert.ToDecimal(txtTotalCharges.Text)
'check for 0 or positive
If decTotalCharges < 0 Then
MessageBox.Show("Please enter a positive value or zero for number of Total Charges!")
Exit Sub
End If
'check for numeric
If IsNumeric(txtTotalCredits.Text) = False Then 'value is not numeric
MessageBox.Show("Please enter a numeric value for Total Credits")
End If
'convert to a numeric data type
decTotalCredits = Convert.ToDecimal(txtTotalCredits.Text)
'check for 0 or positive
If decTotalCredits < 0 Then
MessageBox.Show("Please enter a positive value or zero for total credits!")
End If
'check numeric
If IsNumeric(txtCreditLimit.Text) = False Then 'value is not numeric
MessageBox.Show("Please enter a numeric value for the Credit Limit!")
End If
'convert to a numeric data type
decCreditLimit = Convert.ToDecimal(txtCreditLimit.Text)
'check for a 0 or positive
If decCreditLimit < 0 Then
MessageBox.Show("Please enter a positive value or zero for Credit Limit!")
End If
'check for customers over limit
decCreditMessage = decCreditLimit - (mdecEndingBalance)
'running totals
mdecAllCharges += decTotalCharges
mdecAllCredits += decTotalCredits
'calculate Ending Balance
mdecEndingBalance = Convert.ToDecimal(intBeginningBalance + decTotalCharges - (decTotalCredits))
'display outputs
lblEndingBalance.Text = mdecEndingBalance.ToString("c")
lblAllCharges.Text = mdecAllCharges.ToString("c")
lblAllCredits.Text = mdecAllCredits.ToString("c")
lblCustomersOverLimit.Text = mintCustomersOverLimit.ToString("n0")
End Class
Any Help would be greatly appreciated!
Thanks
You've missed Exit Sub out of the test
If IsNumeric(txtTotalCharges.Text) = False Then 'value is not numeric
MessageBox.Show("Please enter a numeric value for Total Charges!")
End If
You've done it in a few other places as well (as have we all , in fact as do we all :( ). Be worth refactoring with a little helper method or something similar.
If IsValidDecimal(txtTotalCharges.Text, "Total Charges")
' etc
End If