Calculating Prices with List Box - vb.net

Calculating PreTax, Tax, and Total amounts based on items in list box. Here's how it looks currently when executed:
https://drive.google.com/open?id=0B3W0gSES_-fNMmdnU1VTSzR2dFk
Here is the code I have so far:
'load ListBox with test data:
For dblPrices As Double = 1 To 4
lstPrices.Items.Add(dblPrices.ToString("c2"))
Next dblPrices
'calculate pretax total:
Dim dblPretaxTotal As Double = 0
Dim dblSelectedPrice As Double
For intTax As Integer = 0 To lstPrices.Items.Count - 1
lstPrices.SelectedIndex = 0
Dim strPrice As String
strPrice = Convert.ToString(lstPrices.SelectedItem)
Double.TryParse(strPrice, dblSelectedPrice)
dblPretaxTotal = dblSelectedPrice
Next intTax
I only have it programmed to calc and display the PreTax Total currently. It should show $10.00. Any suggestions are welcome.

I think your problem is the failed double conversion.
try this:
dblPretaxTotal += Double.Parse(strPrice, NumberStyles.Currency) * taxRate;
instead of Double.TryParse() without checking for the result. NumberStyles.Currency and a taxrate was also missing.

Related

Showing the name of the most expensive product in vb

i'm pretty new to programming and i got stuck trying to write a program where you type in the name and prices of products and you get back the total, the name+ prices and the most expensive product. Everything works fine except showing the name of the most expensive product.
Here's what i've done
""
Public Class Mrj
Shared Sub main()
Dim i, n As Integer
Console.WriteLine("Enter the number of products")
n = Console.ReadLine()
Dim Products_name(n) As String
Dim Products_price(n), HT, TTC, TVA, max As Decimal
For i = 1 To n
Console.WriteLine("Enter the name of the product " & i)
Products_name(i - 1) = Console.ReadLine()
Console.WriteLine("Enter the price of the product " & i)
Products_price(i - 1) = Console.ReadLine()
HT = HT + Products_price(i - 1)
Next
For i = 1 To n
Console.WriteLine(Products_name(i - 1) & " " & Products_price(i - 1))
Next
TVA = 0.2 * HT
TTC = HT + TVA
Console.WriteLine("Total to pay " & TTC)
max = Products_price(0)
For i = 1 To n - 1
If max > Products_price(i) Then
Else
max = Products_price(i)
End If
Next
Console.WriteLine("The product the most expensive is" & max & Products_name(i))
End Sub
End Class
""
I think the problem is that you are using i to get the name of the most expensive product, but that index i is always i = n since you don't save the index of the maximum value.
You should add a new variable where you store the index everytime you get a new maximum value, and use it in the last line.
Your for loop should be something like this:
Dim max_index As Integer
For i = 1 To n - 1
If max > Products_price(i) Then
Else
max = Products_price(i)
max_index = i
End If
Next
Console.WriteLine("The product the most expensive is" & max & Products_name(max_index))
Try this out and check if it works.
Turn on Option Strict now and forever. Project Properties -> Compile tab. Also for future projects Tools -> Options -> Projects and Solutions -> VB Defaults
You cannot assume that a user will actually enter a number. Test with TryParse.
Arrays in vb.net are declared Products_name(upper bound). In this case that would be Products_name(n-1)
Instead of doing i - 1 for the indexes in the For loop, start our with For i = 0 to n-1
I decided to not use the parallel arrays. Instead I made a tiny class and declared a List(Of Product). I filled the list with the user input setting the Properties of the Product.
I used Linq instead of loops for sums and max. Not necessarily faster but can be accomplished in a single line of code.
I use interpolated strings to display results. When your string is preceded by a $, you can insert variables directly in the text surrounded by braces. The colon following Price indicates a formatting character. Here, I used a C for currency.
Public Class Product
Public Property Name As String
Public Property Price As Decimal
End Class
Sub main()
Dim ProductList As New List(Of Product)
Dim n As Integer
Console.WriteLine("Enter the number of products")
Integer.TryParse(Console.ReadLine, n)
For i = 1 To n
Dim p As New Product
Dim pr As Decimal
Console.WriteLine("Enter the name of the product " & i)
p.Name = Console.ReadLine()
Console.WriteLine("Enter the price of the product " & i)
Decimal.TryParse(Console.ReadLine, pr)
p.Price = pr
ProductList.Add(p)
Next
For Each p In ProductList
Console.WriteLine($"{p.Name} {p.Price:C}")
Next
Dim SubTotal As Decimal = ProductList.Sum(Function(item) item.Price)
Dim Tax As Decimal = 0.2D * SubTotal
Dim Total = SubTotal + Tax
Console.WriteLine($"Total to pay {Total:C}")
Dim Prod = ProductList.OrderByDescending(Function(p) p.Price).FirstOrDefault()
Console.WriteLine($"The product the most expensive is {Prod.Name} at {Prod.Price:C}")
Console.ReadKey()
End Sub

Trying to shorten code in VB.NET

One of my assignments in vb.net is to make a program that takes in 15 inputted "test scores", returns the average, and then returns the corresponding letter grade. I am trying to make this as short as possible, and I remembered a code format that I can use when I am coding in Python (simple example with only three scores):
counter = 0
number = 0
test1,test2,test3 = 0,0,0
for i in [test1,test2,test3]:
print("Enter a test score")
i = int(input())
counter += i
number += 1
average = counter/number
Is there such a code format in VB.NET?
Yes.
Here is a simple sample code which asks user to input number of items and then items one by one. At the end it calculates average of numbers.
Console.WriteLine("Enter number of Items")
Dim numberOfItems As Integer
If Integer.TryParse(Console.ReadLine(), numberOfItems) Then
Dim items As New List(Of Decimal)()
For i As Integer = 1 To numberOfItems
Console.WriteLine("Enter number {0}", i)
Dim num As Decimal
If Decimal.TryParse(Console.ReadLine(), num) Then
items.Add(num)
End If
Next
Console.WriteLine("Average is " + items.Average())
Console.ReadLine()
End If
Please note that I've not included any type of error handling.

I need to add all of the items in a ListBox into a "total" variable

Here is an example of the For loop that I'm trying to run where lstCost is my ListBox that is formed by selecting options from two other ListBoxes and calculating a total for those option to create an item total and totalCost is the variable where I'm trying to save the total of all list items.
Dim totalCost As Integer
For x As Integer = 0 To lstCost.Items.Count - 1
totalCost += Val(lstCost.Items.Item(x))
Next
txtTotalCost.Text = totalCost.ToString
For some reason, I end up with a 0 as my total in my txtTotalCost TextBox. Can anybody think of any reason why?
Dim totalCost As Double = 0
For x As Integer = 0 To lstCost.Items.Count - 1
totalCost += DirectCast(lstCost.Items.Item(x).ToString.trim,Double)
Next
txtTotalCost.Text = totalCost.ToString
depending on your values in listbox you can change it to Decimal if required

vb.net calculations for multiple condition

I need to calculate and get a total amount for a unit with multiple calculation conditions. If I enter an amount in a textbox and press enter the second textbox should display a total amount for the below conditions.
(if unit = 450)
0-100 = 3.00 // 101-200 = 5.00 // 201-300 = 7.00 // over 300 = 10.00
if i press enter after entering the unit as 450 second textbox should display total as 2000.00. I am new to vb.net can anyone help me to do this
(for first 100 => 300.00 / second 100 => 500.00 / third 100 => 700.00 / fourth 100 => 500.00 altogether totally 2000.00)
Here is a simple console application to illustrate the process. The idea is to go from the highest range to the lowest and always check if we have to take items from the current range.
Class AmountLimit
Public Property AmountLowerBound As Integer
Public Property Value As Double
Public Sub New(amountLowerBound As Integer, value As Double)
Me.AmountLowerBound = amountLowerBound
Me.Value = value
End Sub
End Class
Sub Main()
'Specify the values for each range. The first number is the lower bound for the range
Dim amountLimits As New List(Of AmountLimit)
amountLimits.Add(New AmountLimit(0, 3))
amountLimits.Add(New AmountLimit(100, 5))
amountLimits.Add(New AmountLimit(200, 7))
amountLimits.Add(New AmountLimit(300, 10))
Console.Write("Enter the total amount: ")
Dim totalAmount = Integer.Parse(Console.ReadLine())
Dim finalValue As Double = 0
For i As Integer = amountLimits.Count - 1 To 0 Step -1
'Check if our total amount is greater than the current lower bound
Dim currentRange = amountLimits(i)
If (totalAmount > currentRange.AmountLowerBound) Then
finalValue += (totalAmount - currentRange.AmountLowerBound) * currentRange.Value
totalAmount = currentRange.AmountLowerBound
End If
Next
Console.WriteLine(finalValue)
End Sub

How to compute cells using DataGridView

I have 3 column Qty,Price and Amount and i need to compute the amount per line using DataGridView, what are the possible events I may use?
i assumed that Quantity is Cell 0, Price is Cell 1, and Amount is Cell 2
For i As Integer = 0 To DataGridView1.RowCount - 1
Dim xQty as Double = CDBL(DataGridView1.Rows(i).Cells(0).Value)
Dim xPrc as Double = CDBL(DataGridView1.Rows(i).Cells(1).Value)
DataGridView1.Rows(i).Cells(2).Value = xQty * xPrc
Next