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

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

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

Add array values from textboxes and display in a label

enter image description here <<< my interface
I am working on something for my exam next week.
I must use Visual Basic. I am supposed to create an array with an integer and string. Integer = distance String = name. there will be 2 textboxes, 2 labels and 2 buttons.
txtname.text, txtdistance.text, lblname, lbldistance, btninputdata and btnshowcontent
btninputdata should be disabled after filling the 30 arrays and making btnshowcontent to be visible and show all the 30 values (inserted values via textboxes) in lblname and lbldistance.
Whereas they both need to be inserted via a textbox store into the array and then using a btnshowcontent the stored array should be displayed on separate labels of name and distance.
My codes:
Public Class Form1
Dim ara(29) As String
Private Sub Form1_Load(sender As Object, e As EventArgs)
End Sub
Private Sub btninputdata_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btninputdata.Click
If txtname.Text <> "" Then
For h As Integer = 0 To 29
If ara(h) = "" Then
ara(h) = txtname.Text
txtname.Clear()
Exit Sub
End If
Label1.Text = ara.ToString()
Next
MsgBox("arry full")
btninputdata.Visible = False
btnshowcontent.Visible = True
End If
End Sub
Private Sub btnshowcontent_Click(sender As Object, e As EventArgs) Handles btnshowcontent.Click
'ListBox1.Items.Clear()
'ListBox1.Items.AddRange(ara)
''Label1.Text &= ara(I) & ""
End Sub
Private Sub Form1_Load_1(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
End Class
You'll want to start with something like this. Not sure how you're really trying to display everything, though. You'd probably want to do validation on the distance field also.
Public Class Form1
Dim Ara As New List(Of MyGroup)
Private Sub btninputdata_Click(sender As Object, e As EventArgs) Handles btninputdata.Click
If txtName.Text.Trim() <> String.Empty Then
Ara.Add(New MyGroup With {.Name = txtName.Text, .Distance = txtDistance.Text})
If Ara.Count >= 30 Then
'Show/Hide buttons
End If
End If
End Sub
End Class
Public Class MyGroup
Public Name As String
Public Distance As Decimal
End Class
If you truly must use an array you can do something like this:
Public Class Form1
Private Ara(29) As MyGroup
Private Sub btninputdata_Click(sender As Object, e As EventArgs) Handles btninputdata.Click
If txtName.Text.Trim() <> String.Empty Then
Dim EmptyLocation = Array.FindIndex(Ara, Function(x) x Is Nothing)
If EmptyLocation > -1 Then
Ara(EmptyLocation) = New MyGroup With {.Name = txtName.Text, .Distance = txtDistance.Text}
Return
End If
'Show/Hide buttons
'Display the results however.
End If
End Sub
End Class
Public Class MyGroup
Public Name As String
Public Distance As Decimal
End Class

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

remove and reset button for item list

I am trying to create a remove selected item and reset button which removes an item from a list box and reduces the cost of that item in a label. However, The clear button resets the cost and item list text but when clicking a button to add the item again it adds it once into the textbox but brings back the original cost as well as adding the new cost. The Remove selected item button removes the item but not the amount of the cost of that item. What am i doing wrong? Apologies for the bad English.GUI
Option Strict On
Public Class sandwichInterface
Dim DecTotal As Decimal
Private Sub btnCiabatta_Click(sender As Object, e As EventArgs) Handles btnCiabatta.Click
ListBox1.Items.Add("1 Ciabatta £1.50")
ListBox1.Text = ListBox1.Text + ("1 Ciabatta £1.50") + Chr(13)
DecTotal = DecTotal + CDbl(Microsoft.VisualBasic.Right("1 Ciabatta £1.50", 4))
lblTotal.Text = "Total £" + Format(DecTotal, "###.00")
End Sub
Private Sub btnRemove_Click(sender As Object, e As EventArgs) Handles btnRemove.Click
ListBox1.Items.Remove(ListBox1.SelectedItem)
If ListBox1.SelectedItem.Text = "1 Ciabatta £1.50" Then DecTotal = DecTotal - CDbl(Microsoft.VisualBasic.Right("1 Ciabatta £1.50", 4))
lblTotal.Text = "Total £" + Format(DecTotal, "###.00")
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
ListBox1.Items.Clear()
If DecTotal = lblTotal.Text Then lblTotal.Text = "£0.00"
End Sub
End Class
Urgh, it pains me to even read this code but here goes!
Delete this from the add:
ListBox1.Text = ListBox1.Text + ("1 Ciabatta £1.50") + Chr(13)
Swap these 2 lines round, you can't check the value of the selected item after you removed it.:
ListBox1.Items.Remove(ListBox1.SelectedItem)
If ListBox1.SelectedItem.Text = "1 Ciabatta £1.50" Then DecTotal = DecTotal - CDbl(Microsoft.VisualBasic.Right("1 Ciabatta £1.50", 4))
By this:
If DecTotal = lblTotal.Text Then lblTotal.Text = "£0.00"
I can only guess you mean
DecTotal = 0
lblTotal.Text = "£0.00"
I also have no idea why you would do this:
If ListBox1.SelectedItem.Text = "1 Ciabatta £1.50" Then DecTotal = DecTotal - CDbl(Microsoft.VisualBasic.Right("1 Ciabatta £1.50", 4))
Instead of:
If ListBox1.SelectedItem.Text = "1 Ciabatta £1.50" Then DecTotal = DecTotal - 1.50
Even if the latter is still pretty awful!
Your whole approach to this is not nice though, passing around money as part of a string and using Microsoft.VisualBasic.Right and Cdbl to convert it to a float is pretty awful practice to say the least.
This code is not meant to paste into your project but to show you how some things could be done. I created a simple class to add objects to the list box. The Button2.Click shows how you could add items to your list box. You would add them one by one probably from Button events. Button 2 also shows how to get a total for the price. The $ before the string means that it is an interpolated string that can include variables. The :c after Total formats Total to local currency.
The button3.click shows how to remove an item from the list and adjust the total.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
ListBox3.Items.Clear()
With ListBox3.Items
.Add(New FoodItem("Ciabatta", 1.5))
.Add(New FoodItem("Good Bread", 0.5))
.Add(New FoodItem("Great Bread", 2.0))
End With
For Each item As FoodItem In ListBox3.Items
Total += item.Price
Next
lblTotal.Text = $"{Total:c}"
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim SelectedFoodItem As FoodItem = DirectCast(ListBox3.SelectedItem, FoodItem)
Dim d As Double = SelectedFoodItem.Price
ListBox3.Items.Remove(ListBox3.SelectedItem)
Total -= d
lblTotal.Text = $"{Total:c}"
End Sub
End Class
Public Class FoodItem
Public Sub New()
'Default
End Sub
Public Sub New(objFoodName As String, dblPrice As Double)
FoodName = objFoodName
Price = dblPrice
End Sub
Private _FoodName As String
Public Property FoodName As String
Get
Return _FoodName
End Get
Set(value As String)
_FoodName = value
End Set
End Property
Private _Price As Double
Public Property Price As Double
Get
Return _Price
End Get
Set(value As Double)
_Price = value
End Set
End Property
Public Overrides Function ToString() As String
Return $"{_FoodName} {_Price:c}"
End Function
End Class

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.