Invalid Conversion - Cast Exception: 'System.InvalidCastException' - vb.net

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

Related

visual basic: Enter some numbers until a negative value is entered to stop the program

private Sub Command1_Click()
a = InputBox("What is the Number ?", "Input Example"," ")
If a = "-1" Then
End If
End Sub
the whole question is: Enter some numbers until a negative value is entered to stop the program(stop running the what is your number thing). then find the average of the entered numbers.
What I want to do, for now, I want to know how can I make my "a" variable accept any negative value like in the code above it stops when I enter -1 but I want to stop when I enter -3, -10, or any negative value.
There are some helpful answers down below
If you are expecting the usual input to be text then you can use the Double.TryParse method to check if a number was entered. If it was, then you can check if that number is negative, and exit the application if so:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim userMsg As String
userMsg = Microsoft.VisualBasic.InputBox("What is your message?", "Message Entry Form", "Enter your message here", 500, 700)
If userMsg <> "" Then
Dim x As Double
If Double.TryParse(userMsg, x) AndAlso x < 0 Then
Application.Exit()
End If
MessageBox.Show(userMsg)
Else
MessageBox.Show("No Message")
End If
End Sub
The AndAlso operator only looks at the second argument if the first evaluated to True.
If you would like to repeat some portion of code till specific condition is met, you need to use:
While...End While Statement (Visual Basic)
or
Do...Loop Statement (Visual Basic)
It's also possible to write conditional loop using For... Next statement
Dim myNumber As Integer = 0
Dim mySum As Integer = 0
Dim myCounter As Integer = 0
Do
Dim answer As Object = InputBox("Enter integer value", "Getting average of integer values...", "")
'check if user clicked "Cancel" button
If answer <> "" Then
'is it a number?
If Int32.TryParse(answer, myNumber)
If myNumber >=0 Then
mySum += myNumber
myCounter += 1
Else
Exit Do
End If
End If
End If
Loop
Dim average As Double = mySum/myCounter
'you can display average now
Tip: Do not use InputBox, because this "control" is VisualBasic specific. Use custom Form instead. There's tons of examples on Google!

If third character Not IsNumeric

I'm working on a project that displays text on a monitor as a reference but running into some logic trouble. Someone clicks a button which prompts an InputBox into which they insert a bar code with a scanner.
I have 2 types of part numbers, one is like this "11n11110mch" the other is something like this "12311110mch". I need code that tests whether the 3rd character is a number. The end goal is to display the number as "11.(some letter)111.10 MCH" and "123.111.10 MCH" in a TextBox. If I try "11n22210mch", I get an error that says
Conversion from string "n" to type 'Double' is not valid.
at
thirdChara = Mid$(VisPartID, 3, 1)
I am not sure how to correct this or accomplish what I am trying to do.
The code I have:
Public Sub btnScan_Click(sender As Object, e As EventArgs) Handles btnScan.Click
Dim ScanIDRaw As Object
'Clear Scan Value
ScanIDRaw = Nothing
'Display message, title, And default value.
ScanIDRaw = InputBox("Scan CDI", "InputBox")
Do Until ScanIDRaw IsNot ""
ScanIDRaw = InputBox("Part Number Needed, Scan CDI", "InputBox")
Loop
lblCDIPart.Text = ScanIDRaw
HUD.ReferenceCardDataPull()
End Sub
Public Async Sub ReferenceCardDataPull()
Dim PartID As String
Dim VisPartID As String
Dim thirdChara As String
'Other Code
'Something
'Something
VisPartID = Main.lblCDIPart.Text
thirdChara = Mid$(VisPartID, 3, 1)
If thirdChara = Not IsNumeric(thirdChara) Then
VisPartID = VisPartID.Insert(2, ".")
VisPartID = VisPartID.Insert(7, ".")
VisPartID = VisPartID.Insert(10, " ")
VisPartID = VisPartID.ToUpper
lblPart.Text = VisPartID
Else
VisPartID = VisPartID.Insert(3, ".")
VisPartID = VisPartID.Insert(8, ".")
VisPartID = VisPartID.Insert(11, " ")
VisPartID = VisPartID.ToUpper
lblPart.Text = VisPartID
End If
End Sub
If Not isNumeric(thirdChara) Then
But you really should be using VB.Net methods instead of the old VB6 style
dim position3 as integer
thirdChara = VisPartID.SubString(2,1) ' 2 because we're 0 based
if not integer.tryparse(thirdChara, position3) then
'do stuff if not a number
else
'it's a number
end if
The tryparse will return a boolean based upon the parse result. Upon successful parse, it will store the parsed value into the variable (in this case Position3)
I would also recommend turning on Option Strict as that would have informed you right away that you cannot implicitly convert a string to a boolean.
Meaning: The string thirdChara is being tested for equality against as Not (True|False) result from the IsNumeric method.

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

VB.NET - Accumulating Numbers and Calculating Average

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.

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