multiple inputs in text box not totaling - vb.net

I got another super basic question, im trying to total the subtotals of every entry in the txtPrice.Text the user enters, and then refresh the other lables with the updated tax, shipping, and grand total. Its not totaling the subTotal, everything else works fine. Whats up with that?
Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
Dim sglSub As Single
Dim sglTotal As Single
Dim sglSalesTax As Single
Const TAX_RATE As Single = 0.02
Dim bytShippingCharge As SByte = 10
Dim sglCompTotal As Single
Single.TryParse(txtPrice.Text, sglSub)
sglTotal += sglSub
lblSubTotal.Text = sglTotal.ToString("C2")
sglSalesTax = (sglTotal * TAX_RATE)
lblTax.Text = sglSalesTax.ToString("C2")
If sglTotal >= 100 Then
bytShippingCharge = 0
End If
lblShipping.Text = bytShippingCharge.ToString("C2")
sglCompTotal = (sglTotal + sglSalesTax + bytShippingCharge)
lblTotal.Text = sglCompTotal.ToString("C2")
End Sub

Tips
In this line:
sglTotal += sglSub
-Every time you work with a total initialize it to zero before adding a value to it. If not it can leads to undesired result.
-When working with currency is better to use a decimal type instead.
If you want a variable keeps its value declare it shared.
This a little example of how you can use a shared field
Public Class Form1
Shared total As Decimal = 0D
Shared Sub calc()
total += 2
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
calc()
Label1.Text = total.ToString
End Sub
End Class

Related

I can't find the reason for InvalidCastException

I am trying to make an app like an online shop for my project. The code is fine at first(at least for me since there's no errors indications)
But when I run it and press the "Add to Cart" button, it says InvalidCastException and says that I'm trying to convert a string to double even though I am not converting anything
This is what I have so far
Public Class Form1
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim prditem As ListViewItem
Dim price, cartprice As Integer
Dim product As String
If clbParts.SelectedItem = 0 Then
product = "Power Supply"
price = 1
End If
If clbParts.SelectedItem = 1 Then
product = "CPU"
price = 2
End If
....
If rdo512gb.Checked = True Then
product = "Hard Drive (512GB)"
price = 11
End If
If rdo1tb.Checked = True Then
product = "Hard Drice (1TB)"
price = 12
End If
cartprice = Price * numQuantity.Text
prditem = lvCart.Items.Add(product)
With prditem
.SubItems.Add(numQuantity.Text)
.SubItems.Add(cartprice)
End With
If numQuantity.Text = "0" Then
MessageBox.Show("Please put the number of items you want to add", "Cart Error")
End If
MessageBox.Show("Item/s is/are added to your cart", "Cart")
numQuantity.Text = "0"
End Sub
Private Sub btnTotal_Click(sender As Object, e As EventArgs) Handles btnTotal.Click
Dim total As Integer = 0
For i As Integer = 0 To lvCart.Items.Count - 1
Dim quantity = CInt(lvCart.Items(i).SubItems(1).Text)
Dim price = CInt(lvCart.Items(i).SubItems(2).Text)
total += quantity + price
Next
txtTotal.Text = total.ToString("N2")
End Sub
Private Sub cboPayment_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboPayment.SelectedIndexChanged
If cboPayment.SelectedItem = 0 Then
Label10.Enabled = True
cboOnline.Enabled = True
Else
Label10.Enabled = False
cboOnline.Enabled = False
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MessageBox.Show("Your items are being delivered in " + txtHomeAddress.Text + ", " + txtAddress.Text + "\n Please wait for the text confirmation", "Cart Error")
End Sub
End Class
Do yourself a favor and watch a YouTube video on how to debug in Visual Studio!
What you need to do is put a Breakpoint on this line:
cartprice = Price * numQuantity.Text
convert a string to double
You're multplying a number by a String! You want to do something like this:
cartprice = Price * Convert.ToDouble(numQuantity.Text)
I'd personally do a double.TryParse to see if its valid and use the output value when performing the operation.
PS: As a challenge to yourself, try and move all the code logic to a Business Logic class, then use Bingings/BindingControls so the Presentation layer is separated from the logic. That way you can Unit Test the business logic layer!

VB.Net guess user's number from 1 to 1000

I am trying to create a guessing game that guesses the user's number from 1 to 1000. The user inputs if the number is higher or lower than the computer's guess. Based on the user's input, the computer each time halves the amount of the guess (e.g. first guess is 500, second is 250, third 125, etc, etc)
However I have encountered a problem when I am running this program. After pressing 'higher' or 'lower' for a few times, I am unable to change the output any further. I suppose this is to do with amount = amount / 2 reaching a limit where it can barely be added or subtracted into intGuess. I have tried doing amount = (amount / 2) + 1, but that sometimes doesn't allow me to get to a number.
How would I counteract this problem?
Here is my code:
Dim intGuess As Integer = 500
Dim amount As Integer = 500
Dim count As Integer = 0
Private Sub btnLower_Click(sender As Object, e As EventArgs) Handles btnLower.Click
amount = amount / 2
intGuess = intGuess - amount
lblGuess.Text = $"Is your number {intGuess} ?"
count = count + 1
End Sub
Private Sub btnHigher_Click(sender As Object, e As EventArgs) Handles btnHigher.Click
amount = amount / 2
intGuess = intGuess + amount
lblGuess.Text = $"Is your number {intGuess} ?"
count = count + 1
End Sub
Just thought I should add this, but the first guess is 500.
I play this game verbally with my young son. I tell him to guess a number from 1 to 1000 and guarantee I can guess it in 10 or fewer guesses. It is a simple binary search. You can research binary search to come up with an algorithm. It's pretty simple and I've split it up into buttons like you have. Here is my form
The code to make it work is
Private guess As Integer
Private max As Integer
Private min As Integer
Private Sub StartButton_Click(sender As Object, e As EventArgs) Handles StartButton.Click
If Integer.TryParse(MaxTextBox.Text, max) AndAlso
Integer.TryParse(MinTextBox.Text, min) AndAlso
max > min Then
makeGuess()
Else
MessageBox.Show("Error in max or min, cannot continue! Fix max and min and try again.")
End If
End Sub
Private Sub HigherButton_Click(sender As Object, e As EventArgs) Handles HigherButton.Click
min = guess
makeGuess()
End Sub
Private Sub LowerButton_Click(sender As Object, e As EventArgs) Handles LowerButton.Click
max = guess
makeGuess()
End Sub
Private Sub JustRightButton_Click(sender As Object, e As EventArgs) Handles JustRightButton.Click
MessageBox.Show($"That's right, I found your number, it is {guess}!")
End Sub
Private Sub makeGuess()
guess = CInt((max - min) / 2 + min)
GuessLabel.Text = guess.ToString()
End Sub

How do I fix this multidimensional array?

So I need to make a program that displays the monthly sales and totals of three different areas of a company when I click a button. I've added this code, but can't seem to get it right. Can someone advise me on how to fix it. Also, my headings "province, Percentage, Contribution etc" does not display in the list box when the form is loaded.
So basically the values in my .txt files are as follows:
1,Kwazulu Natal,44,120000
1,Gauteng,33,900000
1,Western Cape,23,65000
2,Kwazulu Natal,56,190000
2,Gauteng,25,85000
2,Western Cape,19,64000
3,Kwazulu Natal,54,175000
3,Gauteng,25,80000
3,Western Cape,21,71000
4,Kwazulu Natal,55,188000
4,Gauteng,25,83000
4,Western Cape,20,67000
5,Kwazulu Natal,46,125000
5,Gauteng,31,87000
5,Western Cape,23,65000
6,Kwazulu Natal,53,163000
6,Gauteng,26,80000
6,Western Cape,21,64000
Now they are supposed to show underneath their headings per month (1 - 6). When I run my code, they do not show headings, just the names of the places. It does not give errors
Imports System.IO
Public Class FormMain
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
resultsBox.Items.Clear()
resultsBox.Columns.Add("Province", 100, HorizontalAlignment.Center)
resultsBox.Columns.Add("Percentage", 100, HorizontalAlignment.Center)
resultsBox.Columns.Add("Contribution", 100, HorizontalAlignment.Center)
resultsBox.Columns.Add("Total Cost", 100, HorizontalAlignment.Center)
End Sub
Private Sub ExitBtn_Click(sender As Object, e As EventArgs) Handles ExitBtn.Click
Me.Close()
End Sub
Private Sub ShowResultsBtn_Click(sender As Object, e As EventArgs) Handles ShowResultsBtn.Click
Dim salesReport As String = MonthlyCBox.Text
Dim filereader As New StreamReader("C:\Users\HP Notebook 15\Desktop\main.txt")
Dim details As Array
Dim provinceFound As String = " "
Dim percentageContribute As Integer = 0
Dim monthlySales As Integer = 0
Dim totalvalue As Integer = 0
While filereader.EndOfStream = False
details = filereader.ReadLine().Split(",")
Dim province As String = details(1)
Dim percentage As Decimal = details(2)
Dim monthlyammount As String = details(3)
Dim totalamm As String = details(3)
If details(0) = salesReport Then
resultsBox.Items.Add(New ListViewItem({province, percentage, FormatCurrency(monthlyammount), FormatCurrency(totalamm)}))
End If
End While
End Sub
End Class
I guess you are using ListView, Not List Box. If so, please add
resultsBox.View = View.Details, in load event. That should visible the header text.

Formatting and Computing Numbers in Textbox VB.Net

Hello Everyone Good Afternoon.
I Hope Someone Helps me with my Problem.
I have 3 Textboxes and they are:
GrandTotal.Text
VatAmount.Text
TotalAmount.Text
and 1 NumericUpdown1.Value
Here is the Scenario, As the system goes, there is a code that will trigger and Will put a Number value in GrandTotal.Text and after that, The User will press NumericUpdown1.Value. Every time the user press it A computation will be triggered and a Number value will be Displayed in TotalAmount.Text and VatAmount.Text
To Make it more specific it is like a computation form that will include VAT. For Example.
Grandtotal.text = 2000
and if I press the NumericUpDown to + 1
VatAmount.Text = 20 and TotalAmount.Text = 2020
I hope you get what I mean
and Here is my code for It:
Private Sub NumericUpDown1_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NumericUpDown1.ValueChanged
VatAmount.Text = Val(Grandtotal.text) * NumericUpDown1.Value * 0.01
End Sub
Private Sub VatAmount_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles VatAmount.TextChanged
TotalAmount.Text = Val(VatAmount.Text) + Val(TextBox14.Text)
End Sub
Now I`m done Explaining it here is My Question.
How to put Commas on that Textboxes and Compute It? My Prof. asked that He wants to put commas on the numbers that will bi inputted? No need to literally put Commas. Put it Automatically when value is greater that 3 Digits
How can I put commas in Textboxes and Compute it using the NumericUpdown?
TYSM
This is roughly what you need:
Private Sub GrandTotal_TextChanged(sender As Object, e As EventArgs) Handles GrandTotal.TextChanged
Dim input As Double = Double.Parse(GrandTotal.Text)
Dim inputStringWithCommas As String = input.ToString("N0", CultureInfo.InvariantCulture)
GrandTotal.Text = inputStringWithCommas
Dim vat As Double = Double.Parse(GrandTotal.Text) * NumericUpDown1.Value * 0.01
VatAmount.Text = vat.ToString()
TotalAmount.Text = (Double.Parse(GrandTotal.Text) + vat).ToString("N0", CultureInfo.InvariantCulture)
End Sub
It is similar to what you have, so you should be able to make it work for the NumericUpDown event as well.

Case Statement not working with String Literals

Hi all I am trying to learn VB and am having trouble with some code I am using. I would like my program to output a specific number based on if a check box is checked using case statements but my code is not working.
Public Class frmBTPW
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btncalc.Click
Dim dblhdr As Double
Dim dblfdr As Double
Dim dbltdr As Double
dblhdr = 24
dblfdr = 35
dbltdr = 50
Select Case "Power Wash Rental"
Case "Half Day Rental"
If chkhd.Checked = True Then
txtrc.Text = "poop"
End If
Case "Full Day Rental"
If chkFD.Checked = True Then
txtrc.Text = dblfdr
End If
End Select
End Sub
Private Function Button1_Click() As CheckBox
Throw New NotImplementedException
End Function
End Class
Help would be greatly appreciated.My code isn't outputting anything in the text-box.
Beyond case statements, respectfully I think you should read up on the distinction between a literal value and a variable. "Power Wash Rental" is nothing more than a series of characters, AKA a string: (In this case "P" followed by "o" etc.) Likewise, "Half Day Rental" is a series of characters, "H" followed by "a" etc.)
"Power Wash Rental" is a literal string. So is ""Half Day Rental" and of course they will never match.
Whereas:
Dim A as string
A = TextBox1.text
Now, A is a variable. It is a string which contains whatever series of characters (text) is typed into the textbox.
This is a simple way to do it.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
chkhd.tag = 24 ' store values in the check boxes
chkfd.tag = 35 ' using the tag property
chktd.tag = 50 ' and later add up the values
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btncalc.Click
dim total as double = 0
total += IF(chkhd.checked, cdbl(chkhd.tag), 0)
total += IF(chkfd.checked, cdbl(chkfd.tag), 0)
total += IF(chktd.checked, cdbl(chktd.tag), 0)
msgbox(total)
End Sub
However, I think you might want radio buttons instead of checkboxes.
Checkboxes can all be checked. Radio buttons can only have one at a time.
This solution allows you to keep your price with the checkbox -- you could do this in the form designer instead of form load.
I would recommend reading up on Case Statements. Currently you will never get anywhere as your using a string to what, nothing. You also do not need a case for this... Also if the first condition is true and the last one is as well, the last one win's for setting the text, didn't know if you had this there for a reason or not?
If chkhd.Checked = True Then
txtrc.Text = "poop"
End If
If chkFD.Checked = True Then
txtrc.Text = dblfdr
End If
As others have stated your Case statement isn't working because you are using string literals to compare "Power Wash Rental" to "Half Day Rental" which will always be false. Plutonix was also correct in saying that a ComboBox for the rental duration should be used. The only reason not to be is if you were calculating cumulative rental days/amounts; however in that situation you should be using some sort of NumericUpDown for your multiplier against a time duration.
Here is an example that should help you get started. You could make the structure into a type of keyed collection or make it a wrapper class for a dictionary object which would make be easier to use in code. The following may not be exactly plug-and-play with your project, however it should help give you some ideas on how to handle the situation.
Option Strict On
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.ComboBox1.Items.AddRange({PowerWashRentals.halfDayText, PowerWashRentals.FullDayText, PowerWashRentals.TwoDayText})
AddHandler ComboBox1.SelectedValueChanged, AddressOf Me.ComboBox1_SelectedChanged
End Sub
Private Sub ComboBox1_SelectedChanged(sender As Object, e As EventArgs)
Dim cBox As ComboBox = DirectCast(sender, ComboBox)
Select Case cBox.SelectedItem.ToString
Case PowerWashRentals.halfDayText
Label1.Text = PowerWashRentals.HalfDayPrice.ToString
Case PowerWashRentals.FullDayText
Label1.Text = PowerWashRentals.FullDayPrice.ToString
Case PowerWashRentals.TwoDayText
Label1.Text = PowerWashRentals.TwoDayPrice.ToString
End Select
End Sub
End Class
Public Structure PowerWashRentals
Public Const HalfDayPrice As Double = 24
Public Const FullDayPrice As Double = 35
Public Const TwoDayPrice As Double = 50
Public Const halfDayText As String = "Half Day Rental"
Public Const FullDayText As String = "Full Day Rental"
Public Const TwoDayText As String = "Two Day Rental"
End Structure