Formatting and Computing Numbers in Textbox VB.Net - 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.

Related

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

Visual Basic Avg. Temp Calculator

Ok, so I am super new to visual basic and was not planning on taking it as a class either until they made it a requirement for me to get my technicians certificate at my community college. Literally understand the chapters I have read so far to a T, and then first homework assignment comes up and for the past few days I have been scratching my head as to why on earth it is not working. Here is what the Prof is asking.
Write a program that calculates average daily temperatures and summary statistics. The user will be prompted to enter a Fahrenheit temperature as a value with one decimal place and to select the name of the technician entering the temperature. The user will have the option to see the Celsius equivalent of the entered Fahrenheit temperature. The program will display the average temperature of all entered temperatures. The results are displayed when the user hits ENTER, uses the access key or clicks the Calculate button. The user will be given the opportunity to enter another temperature when the user hits ESC (Clear is the Cancel Button), uses the access key or clicks the Clear button. The user will exit the program by clicking the Exit button or using its access key. The Exit button will also display the summary statistics: 1) the number of temperatures entered by each technician and 2) the average temperature of all entered temperatures. Calculations should only be done if a numeric value between 32.0 and 80.0 (inclusive) degrees for temperature is entered and a technician has been selected.
The graphical side is a breeze with dragging and dropping, then naming the labels, radio buttons, etc... But now that I have assembled my code. Nothing is working. I'm frustrated, confused, and let down. I had no idea this class would be this hard. Here is what I came up with so far code wise. No error messages at all, just not getting any output pretty much.
Option Strict On
Option Strict On
Public Class Form1
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
'Clear App
txtTemp.Clear()
lblAverageTemp.Text = String.Empty
lblCelsius.Text = String.Empty
radDave.Checked = False
radJoe.Checked = False
chkCelsiusTemp.Checked = False
'New Temp Focus
txtTemp.Focus()
End Sub
Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
'End app with display
MessageBox.Show("Dave entered intEntriesDave entries." & ControlChars.CrLf & "Joe entered intEntriesJoe entries." & _
ControlChars.CrLf & "The average temperature is _.", "Status")
Me.Close()
End Sub
Public Sub chkCelsiusTemp_CheckedChanged(sender As Object, e As EventArgs) Handles chkCelsiusTemp.CheckedChanged
'Convert entered Fahrenheit temp to Celsius
Dim dblCelsius As Double
dblCelsius = (CDbl(txtTemp.Text) - 32) * 5 / 9
lblCelsius.Text = CStr(dblCelsius)
End Sub
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim intEntriesDave As Integer = 0
Dim intEntriesJoe As Integer = 0
If radDave.Checked = True Then
intEntriesDave = +1
End If
If radJoe.Checked = True Then
intEntriesJoe = +1
End If
Dim dblAvg As Double
dblAvg = CDbl(txtTemp.Text) / intEntriesDave + intEntriesJoe
lblAverageTemp.Text = CStr(dblAvg)
End Sub
End Class
Hope I figure this out or I can get some help with it. I procrastinated of course, like the idiot I am, and it is due in 11 hours :\
Thanks in advance!
I would use a dictionary to store names along with temperatures.
Place a numericupdown control on your form for the temperature input (numTemp) and a textbox for names tbName and a label lblCelsius for output:
Public Class Form1
Dim temps As New Dictionary(Of String, List(Of Double))
Private Sub btnEnter_Click(sender As Object, e As EventArgs) Handles btnEnter.Click
If numTemp.Value < 32 OrElse numTemp.Value > 80 OrElse tbName.Text = "" Then Exit Sub 'Invalid input
If temps.ContainsKey(tbName.Text) = False Then 'Name is new, create a new list entry
temps.Add(tbName.Text, New List(Of Double))
End If
temps(tbName.Text).Add(numTemp.Value) 'Append the entered temperature
lblCelsius.Text = "In celsius: " & CStr(numTemp.Value - 32) * 5 / 9 'Output the Celsius value
End Sub
Private Sub btnStats_Click(sender As Object, e As EventArgs) Handles btnStats.Click
Dim sb As New System.Text.StringBuilder 'Create the output
For Each k As String In temps.Keys
sb.AppendLine(k & ": " & temps(k).Average)
Next
lblCelsius.Text = sb.ToString
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
temps.Clear() 'Clear the database
End Sub
End Class
Basically everytime you click btnEnter you check your dictionary if the name already entered a value. If not a new entry is created with a new list and the new temperature is just added to the list.
Creating the output is then straightforward with the .Average method of the list.

vb.net code reads lables wrong

Okay, so I am making a game, like cookie clicker, or in my case - http://www.silvergames.com/poop-clicker (don't ask...), so that when you click on the icon in the center, it changes the total value by adding 1. On the side, you have a picture which you click to increase the amount it generates automatically every second.
At the moment I have it like this:
The timer tics every second. If the total amount > the cost of upgrade then it shows the picture of the thing you click to upgrade.
When you click that picture -
The cost is taken away from the total amount.
It changes the amount of times you have used that upgrade by +1.
The automatic upgrades per second is changed by +1.
The Cost is increased by 10.
What is happening is that I click the icon in the middle say 5 times (very quickly) and it only comes up with a total of 3. That in itself is a problem, but the even worse problem is that it shows the picture to click, when i told it to only show when the total value was > 10 (the cost of the upgrade).
I am really confused, and any help will be much appreciated.
Thanks
SkySpear
PS. Here's the Code -
Public Class Form1
Private Sub picPoop_Click(sender As Object, e As EventArgs) Handles picPoop.Click
lblPoops.Text = lblPoops.Text + 1
End Sub
Private Sub picCursor_Click(sender As Object, e As EventArgs) Handles picCursor.Click
lblPoops.Text = lblPoops.Text - lblCursorCost.Text
lblCursorAmmount.Text = lblCursorAmmount.Text + 1
lblPoopsPerSec.Text = lblPoopsPerSec.Text + 1
lblCursorCost.Text = lblCursorCost.Text + 10
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lblCursorAmmount.Text = 0
lblCursorCost.Text = 10
lblBabyAmmount.Text = 0
lblBabyCost.Text = 100
lblBowlAmmount.Text = 0
picCursor.Hide()
tmrSec.Start()
End Sub
Private Sub tmrSec_Tick(sender As Object, e As EventArgs) Handles tmrSec.Tick
If lblPoops.Text > lblCursorCost.Text Then picCursor.Show()
End Sub
End Class
Again, don't ask where this ridiculous idea came from, I can assure you it wasn't mine.
Your main problem with this is that in your Timer sub, you are comparing text to text. In this case, a value of "3" > "21", since text comparisons work on a char by char basis. When this happens, your pictureBox is being shown. As others suggested, you can use any of the string to numeric conversion functions in your timer event to make this work better.
A slightly better approach would be to declare some class level numeric variables that hold each individual value and displays them when needed. As an example
numPoops += 1
lblPoops.Text = numPoops
This will make sure that all math will work correctly.
You are dealing with the Value of the textboxes, not the Text in it.
You should enclose each textbox with VAL() to get its exact value as a number.
Private Sub picPoop_Click(sender As Object, e As EventArgs) Handles picPoop.Click
lblPoops.Text = VAL(lblPoops.Text) + 1
End Sub
Private Sub picCursor_Click(sender As Object, e As EventArgs) Handles picCursor.Click
lblPoops.Text = VAL(lblPoops.Text) - VAL(lblCursorCost.Text)
lblCursorAmmount.Text = VAL(lblCursorAmmount.Text) + 1
lblPoopsPerSec.Text = VAL(lblPoopsPerSec.Text) + 1
lblCursorCost.Text = VAL(lblCursorCost.Text) + 10
End Sub
Private Sub tmrSec_Tick(sender As Object, e As EventArgs) Handles tmrSec.Tick
If VAL(lblPoops.Text) > VAL(lblCursorCost.Text) Then picCursor.Show()
End Sub

multiple inputs in text box not totaling

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

using IF statements to add together prices using VB

I am trying to use if statements to add the prices of a cruises special packages together. I am using check boxes for the packages, so any, from none to all 3 are able to be checked. The packages available are VIP, excursion and restaurant. The price will also depend on the cruise length (7 or 10 day). I am wondering on which format to use, and if I even need to use if statements, but this one has me stumped. If anyone has any ideas on how to make this statement true, I'd appreciate the help. Thank you.
Use a common event handler for your CheckBox's to call an update method like this.
Private Sub CheckBox1_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBox1.CheckedChanged, CheckBox2.CheckedChanged, CheckBox3.CheckedChanged
UpdatePricing()
End Sub
Private Sub UpdatePricing()
Dim total As Double
Dim pricing1 As Double = 2000.99
Dim pricing2 As Double = 4000.49
Dim pricing3 As Double = 6000.19
If CheckBox1.Checked Then total = total + pricing1
If CheckBox2.Checked Then total = total + pricing2
If CheckBox3.Checked Then total = total + pricing3
Label1.Text = Format(total, "$####0.00")
End Sub