remove and reset button for item list - vb.net

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

Related

Input string was not in a correct format in vb,net

I have an error problem in the text label. Is there another solution?
Thanks
Private Sub CalculateGrandTotal()
Dim tot As Double = 0
'error this below code
Dim cash As Double = Double.Parse(lblDisTotal.Text)
For Each item As DataGridViewRow In grid.Rows
tot += Double.Parse(item.Cells(5).Value.ToString())
Next item
lblGrandTotal.Text = (tot * (1 - cash / 100)).ToString("N2")
End Sub
Private Sub BtnRefresh_Click(sender As Object, e As EventArgs) Handles BtnRefresh.Click
lblDisTotal.Text = ""
End Sub
when the button event is refreshed then lblDisTotal does not become blank but becomes "0" then the problem is solved
Private Sub CalculateGrandTotal()
Dim tot As Double = 0
'error this below code
Dim cash As Double = Double.Parse(lblDisTotal.Text)
For Each item As DataGridViewRow In grid.Rows
tot += Double.Parse(item.Cells(5).Value.ToString())
Next item
lblGrandTotal.Text = (tot * (1 - cash / 100)).ToString("N2")
End Sub
Private Sub BtnRefresh_Click(sender As Object, e As EventArgs) Handles BtnRefresh.Click
lblDisTotal.Text = "0"
End Sub
The appropriate solution would be Double.TryParse to handle someone typing "hello world" into your text box if it is not sanitized.
As a rule, you should avoid .parse whereever possible and opt for try parse unless you can guarantee with absolute certainty that your value CAN be parsed into the type you want. Otherwise, utilize tryParse to prevent exceptions that can be prevented.
Private Sub CalculateGrandTotal()
Dim tot As Double = 0
'error this below code
Dim cash As Double
'tryParse returns a boolean indicating successful parsing. You can check for that, however, if it fails, it assigns 0 to your passed in double
Double.TryParse(lblDisTotal.Text, cash)
For Each item As DataGridViewRow In grid.Rows
dim val as double
Double.TryParse(item.Cells(5).Value, val)
tot += val
Next item
lblGrandTotal.Text = (tot * (1 - cash / 100)).ToString("N2")
End Sub
Private Sub BtnRefresh_Click(sender As Object, e As EventArgs) Handles BtnRefresh.Click
lblDisTotal.Text = ""
End Sub

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

Based on menu Items: passing variables from one textbox to another to calculate

Okay, I looked everywhere, and I couldn't find the right terms that matched what I'm looking for. What I'm trying to do is calculate (add) the "Menu item 1" and "Menu item 2" OR "Menu item 9" in the Textbox2 (the bottom textbox). But I have it so it's calculating every item. Is there a way to catch or grab the variables that end up in Textbox1 (top textbox) and calculate it in the Textbox2, instead of calculating ALL of them? Each menu item has it's own price, and I already know how to calculate it with the sales tax. After all, 10 and 9 bucks doesn't add up to 53, does it? I think I did well in 3rd grade math.
Option Strict On
Public Class Form1
'Add a CheckedListBox, a TextBox, and a Button to the form
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
'Set up the menu
CheckedListBox1.Items.Clear()
CheckedListBox1.Items.Add(New MenuItem("Apples", 1D))
CheckedListBox1.Items.Add(New MenuItem("Bananas", 1.1D))
CheckedListBox1.Items.Add(New MenuItem("Cucumbers", 0.56D))
CheckedListBox1.Items.Add(New MenuItem("Daffodils", 0.1D))
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Add up the total
Dim decTotal As Decimal
For Each item As MenuItem In CheckedListBox1.CheckedItems
decTotal += item.Price
Next item
'display the total
TextBox1.Text = "Total = " & decTotal.ToString("C")
End Sub
''' <summary>
''' This class defines a food item on the menu
''' </summary>
''' <remarks></remarks>
Class MenuItem
Public Property Description As String
Public Property Price As Decimal
Sub New(d As String, p As Decimal)
Me.Description = d
Me.Price = p
End Sub
Public Overrides Function ToString() As String
Return Description & " (" & Price.ToString("C") & ")" 'This is what we see in the checkedlistbox
End Function
End Class
End Class
My guess is that your problem is appears to be here:
dectotal = decMenu1 + decMenu2 + decMenu3
dectotal should not add up everything directly it should add on conditional basis.
e.g., ( pseudocode )
dectotal = 0
if(menu1.selected) then dectotal += decMenu1
if(menu2.selected) then dectotal += decMenu2
if(menu3.selected) then dectotal += decMenu3
Debug.Print(dectotal)
EDIT
Try with ArrayList or List(of Decimal)
1) Declare a class variable of type one of them defined above.
2) In each button's handler (menu1,......, menu9) add the corresponding value to arraylist.
e.g., menu1 has price 5$, menu2 has price 3$,..... menu 9 has price 7$.
If Menu9 is pressed, in its event handler, 7 will be added to arraylist.
3) When you calculate and press calculate button, iterate on arraylist items and add up all vales to your `dectotal`.
4) Don;t forget to `clear` arraylist at this point.
Option Strict On
Public Class Form1
Private mdecTotal As Decimal 'running total
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TextBox1.Text &= vbCrLf & "Apple $1.00"
mdecTotal += 1
TextBox2.Text = "Total " & mdecTotal.ToString("C")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
TextBox1.Text &= vbCrLf & "Banana $2.00"
mdecTotal += 2 '$2
TextBox2.Text = "Total " & mdecTotal.ToString("C")
End Sub
'...you get the idea...
Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
'"Clear" button - clear the total
TextBox1.Text = ""
mdecTotal = 0D
TextBox2.Text = "Total " & mdecTotal.ToString("C")
End Sub
End Class

Performing Calculations with Modules in Visual Basic

I am writing a program for my Visual Basic class that is supposed to be able to calculate the final total price for items selected from one list box and added to another. 2 of the items have sales tax that must be added into the final price. The program also has a Module that is supposed to be used to keep record of all taxes and is used to do all tax-related functions.
Here is the most current code.
Option Strict On
Public Class Form1
Private Sub btnAdd_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAdd.Click
If (txtQuantity.Text = "") Then
MessageBox.Show("Please enter a quantity for the item you selected")
ElseIf Not Integer.TryParse(txtQuantity.Text, CInt(txtQuantity.Text)) Then
MessageBox.Show("The quantity entered is not numeric. Please add a numeric quantity.")
Exit Sub
Else
lstPurchased.Items.Add(txtQuantity.Text & " " & lstSale.Text)
End If
End Sub
Private Sub btnCalculate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnCalculate.Click
Dim int As Integer
Dim total As Double = 0
For i As Integer = 0 To lstPurchased.Items.Count - 1
Dim lst() As String = lstPurchased.Items(i).ToString.Split({CChar(" ")}, 2)
Integer.TryParse(lst(0), int)
total += TaxesModule.SalesTax(int, lst(1))
Next
MessageBox.Show(CStr(FormatCurrency(total)))
End Sub
Private Sub btnClear_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnClear.Click
lstPurchased.Items.Clear()
txtQuantity.Clear()
End Sub
End Class
And the most recent code for the module
Option Strict On
Module TaxesModule
Private Const DONUT_TAX As Decimal = CDec(0.083)
Private Const RAISIN_TAX As Decimal = CDec(0.02)
Private Const SS_TAX As Decimal = CDec(0.062) ' <-- you are not using this
Public Function SalesTax(ByVal Quantity As Integer, ByVal item As String) As Double
Dim TotalWithSalesTax As Double
If item = "Wheat Bread" Then
TotalWithSalesTax += (Quantity * 1.15)
ElseIf item = "White Bread" Then
TotalWithSalesTax += (Quantity * 1.05)
ElseIf item = "Donuts" Then
TotalWithSalesTax += (Quantity * (0.5 * DONUT_TAX) + (Quantity * 0.5))
ElseIf item = "Raisins" Then
TotalWithSalesTax += (Quantity * (0.25 * RAISIN_TAX) + (Quantity * 0.25))
End If
Return TotalWithSalesTax
End Function
End Module
As the code is written now, the only problem I'm having is that the TotalWithSalesTax for "Raisins" is not calculating correctly. For example, if I select "Raisins" from the list box and add it with a quantity of 1 to the other list box, the total that is displayed in the message box is $0.00.
I'm starting to think the issue is with the following section of code:
For i As Integer = 0 To lstPurchased.Items.Count - 1
Dim lst() As String = lstPurchased.Items(i).ToString.Split({CChar(" ")}, 2)
Because I have tried making changes such as
For i As Integer = 1 ...
And that caused both Donuts and Raisins to give me a total of $0.00 in the message box. So I'm wondering if maybe how the count is set up is not allowing it to go through the entire list, but I don't know how to fix that?
I'm still really new to Visual Basic, and programming in general really and this is my first time working with modules. Can anybody help me figure out what I'm doing wrong, so I can move onto other parts of the program?
I have modified your code, hope this is what you want. Added comment in the code. Note i have removed all Public variables.
Public Class Form1
Private Sub btnAdd_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAdd.Click
If (txtQuantity.Text = "") Then
MessageBox.Show("Please enter a quantity for the item you selected")
ElseIf Not Integer.TryParse(txtQuantity.Text, txtQuantity.Text) Then
MessageBox.Show("The quantity entered is not numeric. Please add a numeric quantity.")
Exit Sub
Else
lstPurchased.Items.Add(txtQuantity.Text & " " & lstSale.Text)
End If
End Sub
Private Sub btnCalculate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnCalculate.Click
Dim int As Integer
Dim total As Double = 0
'you have to loop through the list to calculate the total
' hope this is what you want
For i As Integer = 0 To lstPurchased.Items.Count - 1
' We split the list item into the quantity and the item name
Dim lst() As String = lstPurchased.Items(i).ToString.Split({CChar(" ")}, 2)
'lst(1) contains the item name
Integer.TryParse(lst(0), int)
total += TaxesModule.SalesTax(int, lst(1))
Next
MessageBox.Show(CStr(FormatCurrency(total)))
End Sub
Private Sub btnClear_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnClear.Click
lstPurchased.Items.Clear()
txtQuantity.Clear()
End Sub
End Class
The module
Module TaxesModule
Private Const DONUT_TAX As Decimal = CDec(0.083)
Private Const RAISIN_TAX As Decimal = CDec(0.02)
Private Const SS_TAX As Decimal = CDec(0.062) ' <-- you are not using this
Public Function SalesTax(ByVal Quantity As Integer, ByVal item As String) As Double
Dim TotalWithSalesTax As Double
If item = "Wheat Bread" Then
TotalWithSalesTax = (Quantity * 1.15)
ElseIf item = "White Bread" Then
TotalWithSalesTax = (Quantity * 1.05)
ElseIf item = "Donuts" Then
TotalWithSalesTax = (Quantity * (0.5 * DONUT_TAX) + (Quantity * 0.5))
ElseIf item = "Raisins" Then
TotalWithSalesTax = (Quantity * (0.25 * RAISIN_TAX) + (Quantity * 0.25))
End If
Return TotalWithSalesTax
End Function
End Module

Calculating Profit in Visual Basic

This program is supposed to read in values from a text file and get a sum of all these values. It is then to use information gathered from a series of check boxes and text boxes to calculate the final profit.
As the code is written now, the profit is only correct if all check boxes are selected, but I need it to be correct if one, two, or all three are checked. Here is the current code
Option Strict On
Imports System.IO
Public Class Form1
Dim sum As Double
Dim fileRead As Boolean
Dim profit As Double
Private Sub menOpen_Click(sender As Object, e As EventArgs) Handles menOpen.Click
Dim ofd As New OpenFileDialog
ofd.Filter = "text files |*.txt|All Files|*.*"
ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
If ofd.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim selectedFileName As String = System.IO.Path.GetFileName(ofd.FileName)
If selectedFileName.ToLower = "profit.txt" Then
Dim line As String
Using reader As New StreamReader(ofd.OpenFile)
While Not reader.EndOfStream
line = reader.ReadLine
Dim value As Integer
If Integer.TryParse(line, value) Then
sum = sum + value
fileRead = True
End If
Console.WriteLine(line)
End While
End Using
Else
MessageBox.Show("You cannot use that file!")
End If
End If
End Sub
Private Sub menExit_Click(sender As Object, e As EventArgs) Handles menExit.Click
Me.Close()
End Sub
Private Sub radSales_CheckedChanged(sender As Object, e As EventArgs) Handles radSales.CheckedChanged
If radSales.Checked Then
profit = sum
End If
End Sub
Private Sub radSandO_CheckedChanged(sender As Object, e As EventArgs) Handles radSandO.CheckedChanged
If radSandO.Checked Then
If Trim(txtWages.Text) = "" Then
txtWages.Text = CStr(0)
End If
profit = (sum - CDbl(txtWages.Text) - CDbl(txtRent.Text) - CDbl(txtUtilities.Text))
End If
End Sub
Private Sub menComputeProfit_Click(sender As Object, e As EventArgs) Handles menComputeProfit.Click
If fileRead = False Then
MessageBox.Show("The file profit.txt has not been read in yet, the profit will be set to zero.")
sum = 0
End If
If chkWages.Checked Then
profit = CDbl(("$" & Val(sum) - (Val(txtWages.Text) + Val(txtRent.Text) + Val(txtUtilities.Text))))
End If
If chkRent.Checked Then
profit = CDbl(("$" & Val(sum) - (Val(txtRent.Text) + Val(txtWages.Text) + Val(txtUtilities.Text))))
End If
If chkUtilities.Checked Then
profit = CDbl(("$" & Val(sum) - (Val(txtUtilities.Text) + Val(txtWages.Text) + Val(txtRent.Text))))
End If
txtAnswer.Text = profit.ToString
End Sub
End Class
Any help would be greatly appreciated.
One of those text inputs is most likely empty (as the error states). Even if it wasn't empty, it could still be an invalid Double value.
In order to safely check if the string can be converted to a double, you can use Double.TryParse, like this:
If Double.TryParse(value, number) Then
Console.WriteLine("'{0}' --> {1}", value, number)
Else
Console.WriteLine("Unable to parse '{0}'.", value)
End If
Before you convert a string to double, check that the string is not empty. This is what error says. Afterwards you should check that the string in the box is actually numeric.
You are using TextChanged Event for txtAnswer
Private Sub txtAnswer_TextChanged(sender As Object, e As EventArgs) Handles txtAnswer.TextChanged
txtAnswer.Text = CStr(profit)
End Sub
So the above code is going to fire itself each time it changes! Just pop profit into txt Answer each time it is calculated
If chkWages.Checked Then
profit = CDbl(("$" & Val(sum) - Val(txtWages.Text)))
txtAnswer.text = profit
End If
If chkRent.Checked Then
profit = CDbl(("$" & Val(sum) - Val(txtRent.Text)))
txtAnswer.text = profit
End If
If chkUtilities.Checked Then
profit = CDbl(("$" & Val(sum) - Val(txtUtilities.Text)))
txtAnswer.text = profit
End If
A bit untidy but that should do it... you will need to do this whenever profit changed. And get rid of the TextChanged event.
UPDATED ANSWER FOR CLARITY
Ok I never add currency symbols so I'm not sure what CDbl(("$" & Val(Sum) - Val(txtWages.Text))) will do as it may treat it as a string character "$" rather than a currency.
Get rid of the "$" and just add the values... if you want to then stick the $ in front once calculation is complete say txtAnswer = $ & profit.toString