Issues with Hospital Charges Function Problems in VB - vb.net

I'm making a program in VB where I have to make three different functions to determine costs from numbers input in my hospital charges form. One to calculate the misc charges(CalcMiscCharges), one to calculate to cost of the hospital stay(CalcChargesOfStay), and one to determine the total charges(CalctotalCharges). With this current code any numbers I put in are being answered with 0 dollars. Can anyone see where my issue lies?
Const DayRate As Decimal = 350
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'declare variables
Dim PhysicalRehab As Decimal
Dim SurgeryCharges As Decimal
Dim LabCharges As Decimal
Dim MedCharges As Decimal
Dim StayCharges As Decimal
Try
'Copy the scores into the variables
StayCharges = CDec(TextBoxLength.Text) * DayRate
MedCharges = CDec(TextBoxMed.Text)
SurgeryCharges = CDec(TextBoxSurg.Text)
LabCharges = CDec(TextBoxLab.Text)
PhysicalRehab = CDec(TextBoxPhy.Text)
Catch
MessageBox.Show("Please enter numeric values", "Error")
Return
End Try
'Find out if box enteries are negative or not
If Convert.ToDecimal(LabCharges) < 0 Then
MessageBox.Show("No Negative Numbers", "Try Agian")
Return
TextBoxLab.SelectAll()
ElseIf Convert.ToDecimal(MedCharges) < 0 Then
MessageBox.Show("No Negative Numbers", "Try Agian")
Return
TextBoxMed.SelectAll()
ElseIf Convert.ToDecimal(SurgeryCharges) < 0 Then
MessageBox.Show("No Negative Numbers", "Try Agian")
Return
TextBoxSurg.SelectAll()
ElseIf Convert.ToDecimal(PhysicalRehab) < 0 Then
MessageBox.Show("No Negative Numbers", "Try Agian")
Return
TextBoxPhy.SelectAll()
ElseIf Convert.ToDecimal(StayCharges) < 0 Then
MessageBox.Show("No Negative Numbers", "Try Agian")
Return
TextBoxLength.SelectAll()
End If
'Sends results to the label
LabelTotal.Text = CalctotalCharges.ToString("c")
End Sub
Function CalcMiscCharges() As Decimal
Return CDec(TextBoxMed.Text) + CDec(TextBoxLab.Text) + CDec(TextBoxPhy.Text) + CDec(TextBoxSurg.Text)
End Function
Function CalcChargesOfStay() As Decimal
Return CalcChargesOfStay = CDec(TextBoxLength.Text) * DayRate
End Function
Function CalctotalCharges() As Decimal
Return CDec(CalctotalCharges = CDec(CalcChargesOfStay() + CalcMiscCharges()))
End Function
Private Sub ButtonExit_Click(sender As Object, e As EventArgs) Handles ButtonExit.Click
Me.Close()
End Sub
Private Sub ButtonClear_Click(sender As Object, e As EventArgs) Handles ButtonClear.Click
TextBoxLab.Clear()
TextBoxLength.Clear()
TextBoxMed.Clear()
TextBoxPhy.Clear()
TextBoxSurg.Clear()
End Sub

It looks to me like you're mixing two different syntaxes in these functions:
Function CalcChargesOfStay() As Decimal
Return CalcChargesOfStay = CDec(TextBoxLength.Text) * DayRate
End Function
Function CalctotalCharges() As Decimal
Return CDec(CalctotalCharges = CDec(CalcChargesOfStay() + CalcMiscCharges()))
End Function
Either only use the Return keyword, or only set the function name to the result.
So it could look like this:
Function CalcChargesOfStay() As Decimal
Return CDec(TextBoxLength.Text) * DayRate
End Function
Function CalctotalCharges() As Decimal
Return CalcChargesOfStay() + CalcMiscCharges()
End Function
Or like this:
Function CalcChargesOfStay() As Decimal
CalcChargesOfStay = (CDec(TextBoxLength.Text) * DayRate)
End Function
Function CalctotalCharges() As Decimal
CalctotalCharges = (CalcChargesOfStay() + CalcMiscCharges())
End Function
But you can't use both syntaxes.

Related

Automatic decimal places in textbox

It looks very strange, but I can't find an online solution for my problem! At least in VB.NET.
Here's the deal:
I have a TextBox in a form (limited to numbers by a KeyPress event) and want to keep two decimal places as long as the user inputs his data.
For example, if the TextBox is blank, then, when the user presses, let's say, "2", the TextBox shows "0,02". Then, if the user presses "7", the TextBox shows "0,27". Then again, by pressing "6", it shows "2,76" and so on...
I managed to do this for one decimal place with the code:
Select Case Me.TextBox.Text
Case ""
Case ","
Me.TextBox.Text = ""
Case Else
Me.TextBox.Text = Strings.Left(Replace(Me.TextBox.Text, ",", ""), Strings.Len(Replace(Me.TextBox.Text, ",", "")) - 1) & "," & Strings.Right(Replace(Me.TextBox.Text, ",", ""), 1)
Me.TextBox.SelectionStart = Len(Me.TextBox.Text)
End Select
Please note that: 1. This code's running on a TextChanged event; 2. I'm from Portugal and here we use a comma (",") instead of a dot (".") for the decimal separator.
Could you help me to adjust my piece of code to work properly with two decimal places?
Any help will be very appreciated. And, as always, thank you all in advance.
Here's a custom class I've made which does what you require:
Public Class FactorDecimal
Private _value As String = "0"
Public DecimalPlaces As Integer
Public Sub AppendNumber(ByVal Character As Char)
If Char.IsNumber(Character) = False Then Throw New ArgumentException("Input must be a valid numerical character!", "Character")
_value = (_value & Character).TrimStart("0"c)
End Sub
Public Sub RemoveRange(ByVal Index As Integer, ByVal Length As Integer)
If _value.Length >= Me.DecimalPlaces + 1 AndAlso _
Index + Length > _value.Length - Me.DecimalPlaces Then Length -= 1 'Exclude decimal point.
If Index + Length >= _value.Length Then Length = _value.Length - Index 'Out of range checking.
_value = _value.Remove(Index, Length)
If _value.Length = 0 Then _value = "0"
End Sub
Public Overrides Function ToString() As String
Dim Result As Decimal
If Decimal.TryParse(_value, Result) = True Then
'Divide Result by (10 ^ DecimalPlaces) in order to get the amount of decimal places we want.
'For example: 2 decimal places => Result / (10 ^ 2) = Result / 100 = x,xx.
Return (Result / (10 ^ Me.DecimalPlaces)).ToString("0." & New String("0"c, Me.DecimalPlaces))
End If
Return "<parse error>"
End Function
Public Sub New(ByVal DecimalPlaces As Integer)
If DecimalPlaces <= 0 Then DecimalPlaces = 1
Me.DecimalPlaces = DecimalPlaces
End Sub
End Class
It works by letting you append numbers to form a long string of numerical characters (for example 3174 + 8 = 31748), then when you call ToString() it does the following:
It parses the long number string into a decimal (ex. "31748" => 31748.0)
It divides the decimal by 10 raised to the power of the amount of decimals you want (for example: 2 decimals => 31748.0 / 102 = 317.48).
Finally it calls ToString() on the decimal with the format 0.x - where x is a repeating amount of zeros depending on how many decimals you want (ex. 2 decimals => 0.00).
NOTE: This solution adapts to the current system's culture settings and will therefore automatically use the decimal point defined in that culture. For example in an American (en-US) system it will use the dot: 317.48, whereas in a Swedish (sv-SE) or Portuguese (pt-PT) system it will use the comma: 317,48.
You can use it like this:
Dim FactorDecimal1 As New FactorDecimal(2)
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
If Char.IsNumber(e.KeyChar) = False Then
e.Handled = True 'Input was not a number.
Return
End If
FactorDecimal1.AppendNumber(e.KeyChar)
TextBox1.Text = FactorDecimal1.ToString()
End Sub
Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown
Dim TargetTextBox As TextBox = DirectCast(sender, TextBox)
e.SuppressKeyPress = True
Select Case e.KeyData 'In order to not block some standard keyboard shortcuts (ignoring paste since the pasted text won't get verified).
Case Keys.Control Or Keys.C
TargetTextBox.Copy()
Case Keys.Control Or Keys.X
TargetTextBox.Cut()
Case Keys.Control Or Keys.A
TargetTextBox.SelectAll()
Case Keys.Back, Keys.Delete 'Backspace or DEL.
FactorDecimal1.RemoveRange(TextBox1.SelectionStart, If(TextBox1.SelectionLength = 0, 1, TextBox1.SelectionLength))
TextBox1.Text = FactorDecimal1.ToString()
Case Else
e.SuppressKeyPress = False 'Allow all other key presses to be passed on to the KeyPress event.
End Select
End Sub
Online test: http://ideone.com/fMcKJr
Hope this helps!
Thank you #Visual Vincent. Your method works fine. However I managed to find a simpler way of doing what I asked by the following code:
Private Sub TextBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox.KeyPress
If Not Char.IsDigit(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then
e.Handled = True
End If
End Sub
Private Sub TextBox_TextChanged(sender As Object, e As EventArgs) Handles TextBox.TextChanged
Select Case Val(Replace(Me.TextBox.Text, ",", "."))
Case 0 : Me.TextBox.Text = ""
Case Else
Me.TextBox.Text = Format(Val(Replace(Me.TextBox.Text, ",", "")) / 100, "0.00")
Me.TextBox.SelectionStart = Len(Me.TextBox.Text)
End Select
End Sub
This piece of code look suspicious simple to me. For now it works fine and does the trick exactly how I wanted. Maybe there's something missing to me, or maybe I wasn't clear enough on the description of my goal.
If you find any flaw on my method, please feel free to point it! I'll appreciate it very much.

What is wrong with my prime function

I'm a beginner in vb and I'm wondering why this code doesn't work.
I wrote the function which I can't seem to find why it doesn't. When I run the program, it seems to print out nothing.
I am supposed to find all the prime numbers between 1 and the input
Option Strict On
Public Class Lab4
Dim endCounter As Integer
Dim sum As Integer
Dim msg As String
Dim input As Integer
Public Function isPrime(input As Integer) As Boolean
endCounter = input - 1
For primeCounter As Integer = 1 To endCounter
If input Mod primeCounter <> 0 Then
Return True
Else
Return False
End If
Next
Return False
End Function
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub btnPrime_Click(sender As Object, e As EventArgs) Handles btnPrime.Click
input = Convert.ToInt32(txtNumber.Text)
msg = "The prime numbers are: "
If input < 0 Then
msg = "Number cannot be negative!"
For inputCounter As Integer = 1 To input
If isPrime(inputCounter) = True Then
msg += inputCounter & " "
End If
Next
MsgBox(msg, , "Prime Number")
End Sub
End If
End Class
This test will always immediately return something on the very first test:
Public Function isPrime(input As Integer) As Boolean
endCounter = input - 1
For primeCounter As Integer = 1 To endCounter
If input Mod primeCounter <> 0 Then
Return True
Else
Return False
End If
Next
Return False
End Function
because you use Return immediately after the 'has modulus' line. Remove the Return True and else lines, so it only returns False if a modulus value is found. The very last line should be Return True – no modulus values are found, so it is a prime.
For this to work, you need to change your test to
If input Mod primeCounter == 0 Then
and change the start test from 1 to 2.
You don't need to test against 1, and you don't need to test all the way up to input or (you probably misunderstood something there) input - 1. The most logical endpoint is ceil(sqrt(input)), the next higher number of the square root of your starting value.

The error is Conversion from string "" to type 'Double' is not valid

Private Sub btntambah_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btntambah.Click
Dim n As Integer
For n = 0 To lv1.Items.Count - 1
If lv1.Items(n).Text = txtkdbrng.Text Then
MsgBox("Data Buku Sudah Ada Dalam List")
Exit Sub
End If
Next
lv1.Items.Add(txtkdbrng.Text)
lv1.Items(n).SubItems.Add(txtnmbrng.Text)
lv1.Items(n).SubItems.Add(txtharga.Text)
lv1.Items(n).SubItems.Add(txtjmlhhrg.Text)
lv1.Items(n).SubItems.Add(txttotal.Text)
lv1.Items(n).SubItems.Add(txtjmlpsn.Text)
lv1.Items(n).SubItems.Add(txtspesifikasi.Text)
txttotal.Text = Format(CDbl(Total()), "###, ###, ###")
ClearBarang()
txtkdbrng.Focus()
End Sub
Function Total() As Double
Dim ttl As Double = 0
If Not Double.TryParse(txttotal.Text, Total) Then
Total = 0
End If
End Function
Private Sub btncetak_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btncetak.Click
If txtnosph.Text = "" Or lv1.Items.Count = 0 Then
MsgBox("Data Belum Lengkap", MsgBoxStyle.Information, "INFORMASI")
Else
Dim nilaikembali1, nilaikembali2 As Integer
objsph.PNoSph = txtnosph.Text
objsph.PTglSph = Format(dtpsph.Value, "yyy-MM-dd")
objsph.PKdCs = txtkdcstmr.Text
nilaikembali1 = objsph.Simpan()
'menyimpan ke tabel Ada menggunakan perulangan
For x As Integer = 0 To lv1.Items.Count - 1
objada.PNoSph = txtnosph.Text
objada.PKdBrg = lv1.Items(x).SubItems(1).Text
objada.PKdBrg = CDbl(lv1.Items(x).SubItems(2).Text)
objada.PKdBrg = CDbl(lv1.Items(x).SubItems(3).Text)
nilaikembali2 = objada.Simpan()
Dim objbarang As New ClsBarang
objbarang.PKdBrg = lv1.Items(x).SubItems(0).Text
Next
If nilaikembali1 = 1 And nilaikembali2 = 1 Then
MsgBox("Data Berhasil Disimpan", MsgBoxStyle.Information, "INFORMASI")
End If
ClearForm()
ClearBarang()
ClearCustomer()
txtnosph.Text = objsph.AutoNumber
End If
End Sub
The problem is with this code:
Function Total() As Double
Dim ttl As Double = 0
If Not Double.TryParse(txttotal.Text, Total) Then
Total = 0
End If
End Function
First off you are using the less well known VB6 style implicit return variable that matches the name of the function, instead use the declared Double in your code named ttl and return the value, like this:
Function Total() As Double
Dim ttl As Double = 0
If Double.TryParse(txttotal.Text, ttl) Then
Return ttl
Else
' Attempted conversion of text to Double type failed
' Do something here, raise error, alert user, etc.
' Returning zero may or may not be acceptable, if it is return zero
Return 0
End If
End Function
Using the Return syntax produces much clearer code, in that it does not assume the reader of your code knows the implicit variable that matches the name of the function concept. Always use Return in a Function.
Note: If a total value of zero is not indicative of a problem, then you will need to alter your function to return Nullable(Of Double) instead of just Double and then you can alter the Else portion of the TryParse() result to this:
Function Total() As Nullable(Of Double)
Dim ttl As Double = 0
If Double.TryParse(txttotal.Text, ttl) Then
Return ttl
Else
' Attempted conversion of text to Double type failed
' So return null
Return Nothing
End If
End Function
Now the caller of your Total function will need to account for Nothing being returned and react accordingly.
This means the variable being explicitly or implicitly casted/converted to double is actually an empty string and cannot be proceed.

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).

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