VB.net: Input string not correct format? - vb.net

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

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

VB.Net InputBox validation negative number

I'm working on a program for a user to input a number in an InputBox. I could write the codes to validate the input value is numeric, but I couldn't came up with a procedure to validate the negative number from InputBox.
Dim UserInput As String = ""
Dim UserInputAsNumber As Integer
Dim SumofTotal As Integer
'to display InputBox
UserInput = (InputBox("Enter a positive number", "Input Needed"))
'to capture userinput is not numeric value
While (Not IsNumeric(UserInput))
UserInput = (InputBox("Enter a positive number", "Input Needed"))
End While
'if userinput is number, convert the value to numeric variable
UserInputAsNumber = CInt(UserInput)
If (UserInputAsNumber <= 0) Then
UserInput = (InputBox("Enter a positive number", "Input Needed"))
Else
SumofTotal = CInt(((UserInputAsNumber * (UserInputAsNumber + 1)) / 2))
'calculation
End If
MessageBox.Show("The sum is " & CStr(SumofTotal))
End Sub
You need to loop through your code until you get a valid positive integer. You can simplify things by using Integer.TryParse to validate the string and convert it to an integer (invalid strings will convert to zero).
Private Sub btnEnterNumbers_Click(sender As Object, e As EventArgs) Handles btnEnterNumbers.Click
Dim UserInput As String = ""
Dim UserInputAsNumber As Integer
Dim SumofTotal As Integer
Do While UserInputAsNumber <= 0
'to display InputBox
UserInput = (InputBox("Enter a positive integer value", "Input Needed", "10"))
'convert to integer, will be zero if not valid integer
Integer.TryParse(UserInput, UserInputAsNumber)
Loop
' Gauss formula to calculate the total of a sequence of numbers from userinput
SumofTotal = CInt(UserInputAsNumber * (UserInputAsNumber + 1) / 2)
MessageBox.Show("The sum of the numbers 1 through " & CStr(UserInputAsNumber) & " is " & CStr(SumofTotal))
End Sub

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: Grade Calculator Program - Getting Ridiculous Values

I am attempting to create a grade calculator program and I am having some two problems:
Getting the right outputs (because I am getting ridiculous numbers) and
Getting my counters to work.
The basic form is basically one enters 7 input grades:
3 exams (weighed 15%, 20%, and 20% respectively)
A project (weighed 10%),
Assignments (weighed 20%),
Peer reviews (weighed 5%) ,
A programming language presentation (weighed 10%)
and the individual is supposed to get an output of their numeric grade, their letter grade, and two counters that count how many people got A's and F's.
For an example when I enter 3 exam grades: 82,87,91; Assignments: 94; Peer reviews: 100; programming language presentation: 90; and final project: 92,
I get a final numeric grade of 253.90 and a letter grade of F when it clearly should be a letter grade of A and numeric 89.90.
My counters also are not working properly because they aren't displaying the count, but I feel like I put it in the right place (displaying outputs). What exactly am I doing wrong here? Here's my code
Option Strict On
Public Class frmGradeCalculator
'declare Constants
Const EXAM1GRADE_WEIGHT As Decimal = 0.15D
Const EXAM2GRADE_WEIGHT As Decimal = 0.2D
Const EXAM3GRADE_WEIGHT As Decimal = 0.2D
Const HOMEWORKGRADE_WEIGHT As Decimal = 0.2D
Const HOMEWORKPEERREVIEW_WEIGHT As Decimal = 0.05D
Const LANGUAGEQUICKREFERENCE_WEIGHT As Decimal = 0.1D
Const FINALPROJECT_WEIGHT As Decimal = 0.1D
'Declare module variables
Dim mdecFinalNumericGrade As Decimal
Dim mstrFinalLetterGrade As String
Dim mintStudentsWithAs As Integer
Dim mintStudentsWithFs As Integer
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
'declare variables
Dim decExam1Grade As Decimal
Dim decExam2Grade As Decimal
Dim decExam3Grade As Decimal
Dim decHomeworkGrade As Decimal
Dim decPeerReviewGrade As Decimal
Dim decLanguageReferenceGrade As Decimal
Dim decFinalProjectGrade As Decimal
Dim decPercent As Decimal
'check for blanks
If (txtExam1Grade.Text) = "" Then
MessageBox.Show("You Can't Leave Exam 1 Blank")
Exit Sub
End If
'check for numeric
If IsNumeric(txtExam1Grade.Text) = False Then 'value is not numeric
MessageBox.Show("Please enter a numeric value for Exam 1!")
Exit Sub
End If
'check for blanks
If (txtExam2Grade.Text) = "" Then
MessageBox.Show("Please enter Exam 2!")
Exit Sub
End If
'check for everything else
If IsNumeric(txtExam2Grade.Text) = False Then 'Value is not numeric
MessageBox.Show("Please enter a numeric value for Exam 2!")
Exit Sub
End If
'check for blanks
If (txtExam3Grade.Text) = "" Then
MessageBox.Show("Please enter Exam 3!")
Exit Sub
End If
'check for numerics
If IsNumeric(txtExam3Grade.Text) = False Then
MessageBox.Show("Please enter a positive numeric value for Exam3!")
Exit Sub
End If
'check for blanks
If (txtHomeworkGrade.Text) = "" Then
MessageBox.Show("Please enter Homework Grade!")
Exit Sub
End If
'check for numerics
If IsNumeric(txtHomeworkGrade.Text) = False Then
MessageBox.Show("Please enter a numeric positive value for Homework Grade!")
Exit Sub
End If
'check for blanks
If (txtPeerReviewGrade.Text) = "" Then
MessageBox.Show("Please enter a Peer Review Grade!")
Exit Sub
End If
'check for numerics
If IsNumeric(txtPeerReviewGrade.Text) = False Then
MessageBox.Show("Please enter a numeric positive value for Peer Review Grade!")
Exit Sub
End If
'check for blanks
If (txtLanguageReferenceGrade.Text) = "" Then
MessageBox.Show("Please enter a Language Reference Grade!")
Exit Sub
End If
'check for numerics
If IsNumeric(txtLanguageReferenceGrade.Text) = False Then
MessageBox.Show("Please enter a numeric positive value for Language Reference Grade!")
Exit Sub
End If
'check for blanks
If (txtFinalProjectGrade.Text) = "" Then
MessageBox.Show("Please enter a Final Project Grade!")
Exit Sub
End If
'check for numerics
If IsNumeric(txtFinalProjectGrade.Text) = False Then
MessageBox.Show("Please enter a numeric positive value for Final Project Grade!")
Exit Sub
End If
'convert data types
decExam1Grade = Convert.ToDecimal(txtExam1Grade.Text)
decExam2Grade = Convert.ToDecimal(txtExam2Grade.Text)
decExam3Grade = Convert.ToDecimal(txtExam3Grade.Text)
decHomeworkGrade = Convert.ToDecimal(txtHomeworkGrade.Text)
decPeerReviewGrade = Convert.ToDecimal(txtPeerReviewGrade.Text)
decLanguageReferenceGrade = Convert.ToDecimal(txtLanguageReferenceGrade.Text)
decFinalProjectGrade = Convert.ToDecimal(txtFinalProjectGrade.Text)
mdecFinalNumericGrade = (decExam1Grade * EXAM1GRADE_WEIGHT) + _
(decExam2Grade * EXAM2GRADE_WEIGHT) + _
(decExam3Grade * EXAM3GRADE_WEIGHT) + _
(decHomeworkGrade * HOMEWORKGRADE_WEIGHT) + _
(decPeerReviewGrade * HOMEWORKPEERREVIEW_WEIGHT) + _
(decLanguageReferenceGrade + LANGUAGEQUICKREFERENCE_WEIGHT) + _
(decFinalProjectGrade + FINALPROJECT_WEIGHT)
'check for 0 or positive
If decExam1Grade < 0 Then
MessageBox.Show("Please enter a positive value or zero for Exam 1!")
Exit Sub
End If
'check for 0 or positive
If decExam2Grade < 0 Then
MessageBox.Show("Please enter a positive value or zero for Exam 2!")
Exit Sub
End If
'check for 0 or positive
If decExam3Grade < 0 Then
MessageBox.Show("Please enter a positive value or zero for Exam 3!")
Exit Sub
End If
'check for 0 or positive
If decHomeworkGrade < 0 Then
MessageBox.Show("Please enter a positive value or zero for Homework Grade!")
Exit Sub
End If
'check for 0 or positive
If decPeerReviewGrade < 0 Then
MessageBox.Show("Please enter a positive value or zero for Peer Review Grade!")
Exit Sub
End If
'check for 0 or positive
If decLanguageReferenceGrade < 0 Then
MessageBox.Show("Please enter a positive value or zero for Language Reference!")
Exit Sub
End If
'check for 0 or positive
If decFinalProjectGrade < 0 Then
MessageBox.Show("Please enter a positive value or zero for Final Project Grade!")
Exit Sub
End If
'make sure values are less than 100
If decExam1Grade > 100 Then
MessageBox.Show("Please enter a value thats 100 or less!")
End If
If decExam2Grade > 100 Then
MessageBox.Show("Please enter a value thats 100 or less!")
End If
If decExam3Grade > 100 Then
MessageBox.Show("Please enter a value thats 100 or less!")
End If
If decHomeworkGrade > 100 Then
MessageBox.Show("Please enter a value thats 100 or less!")
End If
If decPeerReviewGrade > 100 Then
MessageBox.Show("Please enter a value thats 100 or less!")
End If
If decLanguageReferenceGrade > 100 Then
MessageBox.Show("Please enter a value thats 100 or less!")
End If
If decFinalProjectGrade > 100 Then
MessageBox.Show("Please enter a value thats 100 or less!")
End If
'Determine grade per letter
Select Case decpercent
Case Is >= 89.5D
mstrFinalLetterGrade = "A"
mintStudentsWithAs += 1
Case Is >= 79.5D
mstrFinalLetterGrade = "B"
Case Is >= 69.5D
mstrFinalLetterGrade = "C"
Case Is >= 59.5D
mstrFinalLetterGrade = "D"
Case Else
mstrFinalLetterGrade = "F"
mintStudentsWithFs += 1
End Select
lblFinalLetterGrade.Text = mstrFinalLetterGrade
'display outputs
lblFinalNumericGrade.Text = mdecFinalNumericGrade.ToString("f2")
End Sub
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
'clear the texboxes and labels
txtExam1Grade.Clear()
txtExam2Grade.Clear()
txtExam3Grade.Clear()
txtHomeworkGrade.Clear()
txtPeerReviewGrade.Clear()
txtLanguageReferenceGrade.Clear()
txtFinalProjectGrade.Clear()
lblFinalLetterGrade.Text = ""
lblFinalNumericGrade.Text = ""
'setcursor back to top textbox
txtExam1Grade.Focus()
End Sub
Private Sub btnReset_Click(ByVal sende As System.Object, ByVal e As System.EventArgs) Handles btnReset.Click
'reset module level variables
mdecFinalNumericGrade = 0
mstrFinalLetterGrade = ""
mintStudentsWithAs = 0
mintStudentsWithFs = 0
End Sub
Private Sub btnExit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExit.Click
'close the form
End
End Sub
Private Sub frmGradeCalculator_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
End Sub
End Class
Your final grade total is wrong because you're not multiplying the language presentation and final project by their weights, but adding the weight to the score:
Exam1 = 82 * .15 = 12.3
Exam2 = 87 * .20 = 17.4
Exam3 = 91 * .20 = 18.2
Assignments = 94 * .20 = 18.8
Peer Review = 100 * .05 = 5
Language Presentation = 90 + .10 = 90.1
Final Project = 92 + .10 = 92.1
Notice the addition (rather than multiplication) on the last two values. The total is 253.9.
Change the last two calculations for medcFinalNumericGrade to:
(decLanguageReferenceGrade * LANGUAGEQUICKREFERENCE_WEIGHT) + _
(decFinalProjectGrade * FINALPROJECT_WEIGHT)
You will always get an "F" because decpercent is never assigned a value, and therefore the Else Case is executed. Either assign decpercent a value, or use mdecFinalNumericGrade.
For example:
Select Case mdecFinalNumericGrade
instead of
Select Case decpercent
Once you fix the Select Case, your counts should work (unless you reset the form).

Most Efficient Way To Write This Loop VB.Net

Good afternoon all, I am beginning my first forays into programming and have decided to begin with VB.net as I can get VS2010 professional free through MS Dreamspark program.
I have been following some basic tutorials online and am now writing a small program that runs a loop to add all the numbers together between two numbers input by the user.
Below is the code I have written:
Public Class Form1
Private Sub cmdAddNumbers_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAddNumbers.Click
Dim NumberOne As Integer
Dim NumberTwo As Integer
Dim Result As Integer
Dim i As Integer
If Not IsNumeric(txtNumberOne.Text) Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Exit Sub
ElseIf txtNumberOne.Text = 0 Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Exit Sub
ElseIf txtNumberOne.Text > 0 And IsNumeric(txtNumberOne.Text) Then
NumberOne = txtNumberOne.Text
End If
If Not IsNumeric(txtNumberTwo.Text) Then
MsgBox("Please Enter A Valid Number For Number Two")
txtNumberTwo.Clear()
Exit Sub
ElseIf txtNumberTwo.Text < NumberOne Then
MsgBox("Please Enter A Valid Number For Number Two")
txtNumberTwo.Clear()
Exit Sub
ElseIf txtNumberTwo.Text > NumberOne And IsNumeric(txtNumberTwo.Text) Then
NumberTwo = txtNumberTwo.Text
End If
For i = NumberOne To NumberTwo
Result = Result + i
Next i
txtResult.Text = Result
txtNumberOne.Clear()
txtNumberTwo.Clear()
End Sub
End Class
Now, I am wondering if I have written the most efficent If statements to execute this code or if they can be written any simpler with AND/OR statements to possibly remove some of the ElseIf's.
Any insight is greatly appreciated.
Thank you,
Alex
You should start with putting Option Strict On at the top of your code to force yourself to write code without implicit conversions between strings and numbers. An example of a pitfall in your code is where you compare the string value txtNumberTwo.Text to the numeric value NumberOne; it isn't obvious if the string is converted to a number so that the comparison works properly, or if the number is converted to a string so that it does a string comparison instead.
You can use the Int32.TryParse method to parse each number only once instead of three times:
Dim numberOne As Integer
Dim numberTwo As Integer
Dim result As Integer
If Not Int32.TryParse(txtNumberOne.Text, numberOne) Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Exit Sub
ElseIf numberOne <= 0 Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Exit Sub
End If
If Not Int32.TryParse(txtNumberTwo.Text, numberTwo) Then
MsgBox("Please Enter A Valid Number For Number Two")
txtNumberTwo.Clear()
Exit Sub
ElseIf numberTwo < numberOne Then
MsgBox("Please Enter A Valid Number For Number Two")
txtNumberTwo.Clear()
Exit Sub
End If
Your loop is not needed at all. You can calculate the sum directly:
Result = (numberOne + numberTwo) * (numberTwo + 1 - numberOne) / 2
What about:
If Not IsNumeric(txtNumberOne.Text) Or txtNumberOne.Text <= 0 Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Exit Sub
Else
NumberOne = txtNumberOne.Text
End If
If Not IsNumeric(txtNumberTwo.Text) Or txtNumberTwo.Text < NumberOne Then
MsgBox("Please Enter A Valid Number For Number Two")
txtNumberTwo.Clear()
Exit Sub
Else
NumberTwo = txtNumberTwo.Text
End If
Be aware that if NumberOne is equal to Textbox2.Text, NumberTwo is never assigned
i think the best solution for you is just set the textboxes to be able to accept only numbers, that way you can avoid all the checks if the texts is numeric or not and only check if its bigger than zero.
to set the textboxes to accept only numbers copy this function:
Private Function TrapKey(ByVal KCode As String) As Boolean
If (KCode >= 48 And KCode <= 57) Or KCode = 8 Then
TrapKey = False
Else
TrapKey = True
End If
End Function
and in the keypress event of the textboxes add
e.Handled = TrapKey(Asc(e.KeyChar))
If Not IsNumeric(txtNumberOne.Text) Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Exit Sub
ElseIf txtNumberOne.Text = 0 Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Exit Sub
ElseIf txtNumberOne.Text > 0 And IsNumeric(txtNumberOne.Text) Then
NumberOne = txtNumberOne.Text
End If
The third If is superflious. We know it must be IsNumeric, as it passed the first If, and we know it cannot be 0, as it passed the second If. (You also make no allowances at all, if it happens to be negative)
Now, it been a while since I last did VB.Net, but I'm pretty sure it still have a distinct between strings & integers, which means txtNumberOne.Text = 0 shouldn't even compile.
And also, why are you making your users guess what a "valid number" is?
Dim numberOne as Integer
If IsNumeric(txtNumberOne.Text) Then
numberOne = CInt(txtNumberOne.Text)
else
numberOne = -1;
End If
If numberOne < 1
MsgBox("Please Enter A Positive Number For Number One")
txtNumberOne.Clear()
Exit Sub
End If
Dim doub As Double
If Not (Double.TryParse(txtNumberOne.Text, doub) AndAlso doub > 0) Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Else
NumberOne = doub
End If
If Not (Double.TryParse(txtNumberTwo.Text, doub) AndAlso doub > 0) Then
MsgBox("Please Enter A Valid Number For Number Two")
txtNumberTwo.Clear()
Else
NumberTwo = doub
End If
I think this is waht you are looking for
Result = (NumberTwo * (NumberTwo + 1) / 2) - ((NumberOne - 1) * (NumberOne) / 2)