Hospital Charges Visual Basic - vb.net

I'm making a visual basic project for school that calculates your total during a hospital stay. It works for the most part, but I'm supposed to be getting an error message when a negative number is being entered and I'm not getting that message. Here is the coding as I have it right now:
Public Class Form1
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
'close form
Me.Close()
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
'clear form
txtLab.Clear()
txtMedication.Clear()
txtPhysical.Clear()
txtStay.Clear()
txtSurgical.Clear()
txtStay.Focus()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'class level declaration
Const DayRate As Decimal = 350D 'cost per day
'declare variables
Dim Physical As Decimal
Dim Surgical As Decimal
Dim Lab As Decimal
Dim Medication As Decimal
Dim Stay As Decimal
Try
'Copy the scores into the variables
Stay = CDec(txtStay.Text) * DayRate
Medication = CDec(txtMedication.Text)
Surgical = CDec(txtSurgical.Text)
Lab = CDec(txtLab.Text)
Physical = CDec(txtPhysical.Text)
Catch
MessageBox.Show("Please enter numeric values")
Return
'Find out if box enteries are negative or not
If Convert.ToDecimal(Lab) < 0 Then
MessageBox.Show("No Negative Numbers", "Try Agian")
Return
txtLab.SelectAll()
ElseIf Convert.ToDecimal(Medication) < 0 Then
MessageBox.Show("No Negative Numbers", "Try Agian")
Return
txtMedication.SelectAll()
ElseIf Convert.ToDecimal(Surgical) < 0 Then
MessageBox.Show("No Negative Numbers", "Try Agian")
Return
txtSurgical.SelectAll()
ElseIf Convert.ToDecimal(Physical) < 0 Then
MessageBox.Show("No Negative Numbers", "Try Agian")
Return
txtPhysical.SelectAll()
ElseIf Convert.ToDecimal(Stay) < 0 Then
MessageBox.Show("No Negative Numbers", "Try Agian")
Return
txtStay.SelectAll()
End If
End Try
End Sub
Function CalcStayCharges() As Decimal
CalcStayCharges = (CDec(txtStay.Text) * 350)
End Function
Function CalcMiscCharges() As Decimal
CalcMiscCharges = CDec(txtMedication.Text) + CDec(txtLab.Text) + CDec(txtPhysical.Text) + CDec(txtSurgical.Text)
End Function
Function CalctotalCharges() As Decimal
CalctotalCharges = (CalcStayCharges() + CalcMiscCharges())
End Function
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
'calculates total of stay
Dim decTotal As Decimal
decTotal = CalctotalCharges()
lblTotal.Text = decTotal.ToString("c")
End Sub
End Class

The code you have in the Catch clause doesn't execute because no exceptions occur. You should move your If.. Else.. statements before the Catch clause.

Related

VB Entering a Non_Numeric value crashes the program

Please consider adding a description to this question to attract more helpful responses.
Public Class Form1
Private Sub BtnCalculateRevenue_Click(sender As Object, e As EventArgs) Handles BtnCalculateRevenue.Click
Dim intvalue As Integer = CInt(TxtInputClassA.Text)
Dim intvalue2 As Integer = CInt(TxtInputClassB.Text)
Dim intvalue3 As Integer = CInt(TxtinputClassC.Text)
Dim total As Double
Try
LblStatus.Text = String.Empty
LblClassAResult.Text = (intvalue * 15).ToString("c")
LblClassBResult.Text = (intvalue2 * 12).ToString("c")
LblClassCResult.Text = (intvalue3 * 9).ToString("c")
total = CDbl((intvalue * 15) + (intvalue2 * 12) + (intvalue3 * 9))
LblTotal.Text = total.ToString("c")
Catch
LblStatus.Text = "Please Enter a Number"
End Try
End Sub
Private Sub BtnExit_Click(sender As Object, e As EventArgs) Handles BtnExit.Click
Me.Close()
End Sub
Private Sub BtnClear_Click(sender As Object, e As EventArgs) Handles BtnClear.Click
TxtInputClassA.Clear()
TxtInputClassB.Clear()
TxtinputClassC.Clear()
LblClassAResult.Text = String.Empty
LblClassBResult.Text = String.Empty
LblClassCResult.Text = String.Empty
LblTotal.Text = String.Empty
End Sub
End Class
VB Entering a Non_Numeric value crashes the program
Validation is built right into Windows Forms so you should make use of it. If you want to force the user to enter numbers in each of three TextBoxes then you can do this:
Private Sub TextBoxes_Validating(sender As Object, e As ComponentModel.CancelEventArgs) Handles TextBox3.Validating, TextBox2.Validating, TextBox1.Validating
Dim tb = DirectCast(sender, TextBox)
If Not Integer.TryParse(tb.Text, Nothing) Then
'Select all the invalid text and highlight it.
tb.SelectAll()
tb.HideSelection = False
MessageBox.Show("Please enter a whole number",
"Invalid Input",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation)
'Remove highlight when TextBox is not focused.
tb.HideSelection = True
'Don't let the control lose focus while data is invalid.
e.Cancel = True
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If ValidateChildren() Then
'All data is valid so proceed.
Dim n1 = CInt(TextBox1.Text)
Dim n2 = CInt(TextBox2.Text)
Dim n3 = CInt(TextBox3.Text)
'...
End If
End Sub
The ValidateChildren method will raise the Validating event for every control on the form and return False if any fail validation, i.e. e.Cancel is set to True in any event handlers, so that ensures that even controls that never received focus will be validated before the data is used.
Its bombing out on your cast "CInt(*value*)" so you can fix the code a couple ways. You can move your try above the casts like...
Try
Dim intvalue As Integer = CInt(TxtInputClassA.Text)
Dim intvalue2 As Integer = CInt(TxtInputClassB.Text)
Dim intvalue3 As Integer = CInt(TxtinputClassC.Text)
Dim total As Double
LblStatus.Text = String.Empty
You can do a data validation on your inputs and exit if they aren't all numeric (put this above your Dim intvalue code)
For Each value As String In {TxtInputClassA.Text, TxtInputClassA.Text, TxtInputClassA.Text}
If Not IsNumeric(TxtInputClassA.Text) Then
LblStatus.Text = "Please Enter a Number"
Exit Sub
End If
Next
Instead of casting as an int, use the tryparse method on Int32...
Dim intvalue As Integer
If Not Int32.TryParse(TxtInputClassA.Text, intvalue) Then
Exit Sub
End If
Or you could intercept the keypresses on each text box so that only numbers can be entered
Private Sub TxtInputClassA_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TxtInputClassA.KeyPress
If Not Char.IsDigit(e.KeyChar) Then
e.Handled = True
End If
End Sub
You can make that routine universal and append the event handler for all three text boxes like...
Private Sub EnforceOnlyNumericKeyPresses(sender As Object, e As KeyPressEventArgs) Handles TxtInputClassA.KeyPress, TxtInputClassB.KeyPress, TxtInputClassC.KeyPress
If Not Char.IsDigit(e.KeyChar) Then
e.Handled = True
End If
End Sub
Choose your favorite or do all of them, lots of choices.
Replace your textboxes with NumericUpDown controls and retrieve their .Value for your calculation. NUDs don't allow non numeric input and can have a fixed number of decimal places which may also be useful in a financial context

How do I multiply a user's text by an array item selected from a menu?

I'm trying to write a gross pay calculator, and can't quite get the coding right to multiply the user entered number by the selected pay rate.
Everything I try based off tweaking other project's code to fit my current project just returns errors.
Private strCode(,) As String = {{“P23”, “10.5”},
{“P56”, “12.5”},
{“F45”, “14.25”},
{“F68”, “15.75”},
{“F96”, “17.65”}}
Private Sub txtHours_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtHours.KeyPress
' Accept only numbers, the period, and the Backspace key.
If (e.KeyChar < "0" OrElse e.KeyChar > "9") AndAlso e.KeyChar <> "." AndAlso e.KeyChar <> ControlChars.Back Then
e.Handled = True
End If
End Sub
Private Sub BtnCal_click(sender As Object, e As EventArgs) Handles btnCalc.Click
Const V As strCodes(,)(,)
Dim txtHours As Decimal = txtHours.text
lblGross.Text = {{txtHours.Text} * {lstCodes.SelectedIndex}}
End Sub
Whether I declare the txtHours as double, decimal, it always returns the error that it can't be converted. The bottom portion of the code is non-working, but is essentially what I need to happen with this code.
I would expect to see something more like:
Private Sub BtnCal_click(sender As Object, e As EventArgs) Handles btnCalc.Click
If lstCodes.SelectedIndex <> -1 Then
Dim quantity, rate As Double
If Double.TryParse(txtHours.Text, quantity) AndAlso Double.TryParse(lstCodes.SelectedItem, rate) Then
Dim price As Double = quantity * rate
lblGross.Text = price
Else
MessageBox.Show("Invalid Quantity and/or Rate!")
End If
Else
MessageBox.Show("No Rate Selected!")
End If
End Sub
I created a structure to hold your data. A list of the type of structure then can keep the data and a List(Of T) can be bound to a list box. The display and value members are set to the properties of the structure. When an item is selected in the list box we can get the .SelectedValue and use it in the calculation.
Public Structure PayRate
Public Property RateClass As String
Public Property PayRate As Decimal
Public Sub New(rClass As String, pRate As Decimal)
RateClass = rClass
PayRate = pRate
End Sub
End Structure
Private PayRates As New List(Of PayRate)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
PayRates.Add(New PayRate(“P56”, 12.5D))
PayRates.Add(New PayRate(“F45”, 14.25D))
PayRates.Add(New PayRate(“F68”, 15.75D))
PayRates.Add(New PayRate(“F96”, 17.65D))
ListBox1.DataSource = PayRates
ListBox1.DisplayMember = "RateClass"
ListBox1.ValueMember = "PayRate"
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Hours As Decimal
If Decimal.TryParse(TextBox1.Text, Hours) Then
Label1.Text = (Hours * CDec(ListBox1.SelectedValue)).ToString("000.00")
Else
MessageBox.Show("Please enter a valid number in Hours box.")
End If
End Sub

I am working on vb.net and basic thing which I am doing is Deposit and withdraw of amounts

So If txtFirstName.Text = String.Empty And
txtLastName.Text = String.Empty And
txtAmount.Text = String.Empty Then
MsgBox("Please enter Information")
this part doesnt work at all, when i tried keeping the breakpoint and look at how it is working, It came out true but the msgbox was never shown.
and the deposit and withdraw functions work as strings.
Also I want to know How I can keep my code in different class and use it in this class for deposit and withdraw buttons.
Here is the code that I wrote:
Option Strict On
Option Explicit On
Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.Load
if not IsPostBack then
lblFirstName.Focus()
End Sub
Protected Sub btnConfirm_click(ByVal sender As Object, ByVal e As
System.EventArgs) Handles btnConfirm.Click
If txtFirstName.Text = String.Empty And
txtLastName.Text = String.Empty And
txtAmount.Text = String.Empty Then
MsgBox("Please enter Information")
Else
doConfirm()
End If
End Sub
Private Sub doConfirm()
If rbtndeposit.Checked Then
txtBalance.Text += (txtAmount.Text)
ElseIf rbtnWithdraw.Checked Then
if txtAmount.text <= txtBalance.text then
txtBalance.text -= txtAmount.text
else
msgBox("Funds not sufficient")
End If
End If
End Sub
End Class
Firstly,Your logic with your text input is a bit flawed, the AND should be OrElse:
Protected Sub btnConfirm_click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnConfirm.Click
If txtFirstName.Text.Length < 1 OrElse _
txtLastName.Text.Length < 1 OrElse _
txtAmount.Text.Length < 1 Then
MsgBox("Please enter Information")
Else
doConfirm()
End If
End Sub
Secondly, you are trying to do mathematical calculations with text values. Convert your input to the correct data type when doing calculations.
Private Sub doConfirm()
If rbtndeposit.Checked Then
txtBalance.Text = Cstr(Cdbl(txtBalance.Text) + Cdbl(txtAmount.Text))
ElseIf rbtnWithdraw.Checked Then
If CDbl(txtAmount.text) <= Cdbl(txtBalance.text) Then
txtBalance.text = Cstr(Cdbl(txtBalance.text) - Cdbl(txtAmount.text))
Else
msgBox("Funds not sufficient")
End If
End If
End Sub
You should how ever use tryparse to check if the input for the amount is valid or your code will crash when the input is not valid, for example:
Dim amount As Double
If Double.TryParse(txtAmount.text, amount) Then
If rbtndeposit.Checked Then
txtBalance.Text = Cstr(Cdbl(txtBalance.Text) + amount)
ElseIf rbtnWithdraw.Checked Then
If amount <= Cdbl(txtBalance.text) then
txtBalance.text = Cstr(Cdbl(txtBalance.text) - amount)
else
msgBox("Funds not sufficient")
End If
End If
Else
MessageBox.Show("Invalid amount entered.")
End if
As for storing your procedure is a separate class, I think just creating functions should be sufficient:
Private Sub Button1_WithDraw(sender As Object, e As EventArgs) Handles Button1_WithDraw.Click
txtBalance.Text = Withdraw(CDbl(txtAmount.Text), Cdbl(txtBalance.text)).ToString
End Sub
Private Function Withdraw(ByVal Amount As Double, ByVal Balance As Double) As Double
Balance = Balance - Amount
Return Balance
End Function

VB Program not working, should be simple

This is a homework assignment, as far as I know I have everything I'm supposed to do. Yet it doesn't work for some reason. If I input "50000" for the Property Value, ".6" for the Assessment Percent, and ".7" for the Assessment Rate I should get "$210" for Property Tax, yet I keep getting only a zero, not sure what I missed. It's not due until Sunday, so if you only want to give me a hint that would also be appreciated. I've gone over the instructions and the code a few times and I'm still not seeing my mistake. I keep looking at "propertytaxLabel.Text = CDec(decTax)" like I messed up something there also.
Public Class Form1
Private Sub clearButton_Click(sender As Object, e As EventArgs) Handles clearButton.Click
valueTextBox.Clear()
percentTextBox.Clear()
rateTextBox.Clear()
propertytaxLabel.Text = ""
End Sub
Private Sub exitButton_Click(sender As Object, e As EventArgs) Handles exitButton.Click
Me.Close()
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
Dim result As DialogResult
result = MessageBox.Show("Are you sure?", "Exit", MessageBoxButtons.YesNo)
If result = DialogResult.No Then
e.Cancel = True
End If
End Sub
Private Sub calculateButton_Click(sender As Object, e As EventArgs) Handles calculateButton.Click
Try
Dim decValue, decPercent, decRate, decTax As Decimal
decValue = CDec(valueTextBox.Text)
decPercent = CDec(percentTextBox.Text)
decRate = CDec(rateTextBox.Text)
propertytaxLabel.Text = CStr(decTax)
If proceduresRadioButton.Checked = True Then
TaxCalcProc(decValue, decPercent, decRate, decTax)
Else
decTax = TaxCalcFunc(decValue, decPercent, decRate)
End If
FormatCurrency(decTax)
Catch ex As Exception
MessageBox.Show("Error: Did you enter the data correctly?")
End Try
End Sub
Private Sub TaxCalcProc(ByVal propVal As Decimal, ByVal perc As Decimal, ByVal rate As Decimal, ByRef tax As Decimal)
Dim AssessedValue As Decimal
Try
AssessedValue = propVal * perc
tax = AssessedValue / 100 * rate
If rate > 1 Or perc > 1 Then
Throw New Exception("Tax Greater Than Value. Did you use the decimal point?")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Function TaxCalcFunc(ByVal propVal As Decimal, ByVal perc As Decimal, ByVal rate As Decimal) As Decimal
Dim tax As Decimal
Dim AssessedValue As Decimal
Try
AssessedValue = propVal * perc
tax = AssessedValue / 100 * rate
If rate > 1 Or perc > 1 Then
Throw New Exception("Tax Greater Than Value. Did you use the decimal point?")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Return 0
End Try
Return Tax
End Function
End Class
You are printing out your decTax to your label after you are declaring it, but not after you are calculating it.
Try moving propertytaxLabel.Text = CStr(decTax) to after FormatCurrency(decTax) inside your button click event.
My VB is rusty, but you're not by any chance trying to convert "50,000" to a number, and it's failing because it has a comma in it? Most string -> int and string -> float conversions (in other languages) don't like commas.
First, you should research debugging and setting breakpoints with Visual Studio. It would make solving this very easy. Barring that, you can isolate and test your function with the following:
Private Sub calculateButton_Click(sender As Object, e As EventArgs) Handles calculateButton.Click
Dim decTax As Decimal
TaxCalcProc(50000D, 0.6D, 0.7D, decTax)
Dim resultString = Format(decTax, "C")
MessageBox.Show("decTax = " + resultString, "Test", MessageBoxButtons.Ok)
End Sub
Also, change:
AssessedValue / 100 * rate
to:
AssessedValue / 100D * rate
You probably have an unintentional case to Int because of the divide by 100. 100D tells the compiler that you want a decimal number.

Not Calculating or Showing MessageBox

I have an assignment I have been working on in VB. I have attached the assignment below:
(I would've attached the image but I cannot because I am a new user)
Assignment Question
(http://i.imgur.com/LPZre2F.jpg)
I have written all of the code but for some reason I cannot get the calculate button to calculate anything. Nor, can I get the messagebox to show in the Calculate button when there is no input in the NameTextBox or the PieceTextBox.
Can someone spot something that I am missing on why this may not be working?
Public Class Form1
'Declare Variables
Dim Pieces As Integer
Dim AmtEar As Decimal
Dim NoPieces As Decimal = 0
Dim totPay As Decimal = 0
Dim avgPay As Decimal = 0.0
'Declare Confirm Message Variable
Dim confirmOpt As DialogResult
Private Sub CalculateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Try
'Declare constant rates paid out
Const priceRate1 As Decimal = 0.5
Const priceRate2 As Decimal = 0.55
Const priceRate3 As Decimal = 0.6
Const priceRate4 As Decimal = 0.65
'Check the blank fields (name and number of pieces)
If NameTextBox.Text = "" Then
MessageBox.Show("Please Enter Name:")
Else
If PieceTextBox.Text = "" Then
MessageBox.Show("Please Enter Number of Pieces Produced")
Else
'Count number of pieces
NoPieces += 1
'Read number of pieces
Pieces = Integer.Parse(PieceTextBox.Text)
'Use select case for given constraints
'calculate earned amount for each
Select Case Pieces
Case 1 To 199
AmtEar = priceRate1 * Pieces
totPay += AmtEar
Case 200 To 399
AmtEar = priceRate2 * Pieces
totPay += AmtEar
Case 400 To 599
AmtEar = priceRate3 * Pieces
totPay += AmtEar
Case Is >= 600
AmtEar = priceRate4 * Pieces
totPay += AmtEar
Case Else
MessageBox.Show("Number of Pieces Produced Must Be Numeric")
End Select
'Display amount earned
AmtTextBox.Text = AmtEar.ToString("C")
End If
End If
'Exception for wrong input
Catch ex As FormatException
MessageBox.Show("Enter Valid Data", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Try
End Sub
Private Sub SummaryButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SummaryButton.Click
'calculates summary total
If (NoPieces >= 1) Then
'calculate and update total pieces, total pay and average pay
avgPay = totPay / NoPieces
TotalProducedTextBox.Text = NoPieces.ToString()
TotlPayTextBox.Text = NoPieces.ToString("C")
AveragePayTextBox.Text = avgPay.ToString("C")
Else
'Otherwise display message
MessageBox.Show("Enter at Least One Employee Data", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
Private Sub ClearButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ClearButton.Click
'Clear name and number of pieces
NameTextBox.Clear()
PieceTextBox.Clear()
AmtTextBox.Clear()
End Sub
Private Sub ClearAllButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ClearAllButton.Click
'If no data is available
If NoPieces = 0 Then
MessageBox.Show("No Data Available To Delete")
Else
'Confirm option message
confirmOpt = MessageBox.Show("Are You Sure You Want To Delete Summary", "Confirm", MessageBoxButtons.YesNo)
'Check if yes then clear all inputs and totals
If confirmOpt = DialogResult.Yes Then
avgPay = 0
totPay = 0
NoPieces = 0
NameTextBox.Clear()
PieceTextBox.Clear()
AmtTextBox.Clear()
TotalProducedTextBox.Clear()
TotlPayTextBox.Clear()
AveragePayTextBox.Clear()
End If
End If
End Sub
End Class
You are missing the Click-handle for that button.
Change this:
Private Sub CalculateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
to something like this:
Private Sub CalculateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CalculateButton.Click