VB Program not working, should be simple - vb.net

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.

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 to compare textbox value to txt file

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim linenumber0 As Integer
linenumber0 = 0
Dim mass As Double
mass = (File.ReadAllLines("225.txt").ElementAt(linenumber0).ToString)
If (Math.Abs((cDbl(TextBox1.Text) - mass < 0.5) Then
TextBox1.BackColor = Color.Green
End If
Im getting an error conversing from string to double is not valid. It is probably a simple solution but i cant see it right now
Your error occurs because the data read from the file is a String, however you are attempting to assign it to a variable declared as Double.
You can use TryParse to convert the String to Double, avoid errors and provide appropriate feedback.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim lineNumber0 As Integer
Dim mass As Double
Dim input As Double
If Double.TryParse(File.ReadAllLines("225.txt").ElementAt(linenumber0), mass) Then
If Double.TryParse(TextBox1.Text, input) AndAlso Math.Abs(input - mass) < 0.5 Then
TextBox1.BackColor = Color.Green
End If
Else
'Bad file input
End If
'...
End Sub
I think that when you set the value to mass is catching a String, so parse it with a simple CDbl, like this
mass = cDbl(File.ReadAllLines("225.txt").ElementAt(linenumber0).ToString)
I supose that with this fix it will works.
Just in case, surround it with a TRY CATCH in case what it reads is not valid

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

Hospital Charges Visual Basic

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.