using IF statements to add together prices using VB - vb.net

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

Related

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.

Dynamically updating a progress bar in VB

Hello I am a novice / mediocre VB programmer and I made a timer that simply need to update it self every second.
I started having doubts about weather or not it was working so I applied a msg box to my timers code it went off every second updating it self but the progress bar wont? why?
Dim power As PowerStatus = SystemInformation.PowerStatus
Dim percent As Single = power.BatteryLifePercent
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer.Tick
ProgressBar1.Value = percent * 100
Label1.Text = percent * 100
End Sub
I have a power status and percent that takes the status and turn into a usable percentage then the progress bar uses that percentage but isnt updating like the msgBOX does why?
Well, your timer is probably working well and all, but you don't show where/how you get the updated value of SystemInformation.PowerStatus.BatteryLifePercent.
Maybe you're doing this somewhere else in your code, but as it is posted, you're always displaying the same value, so of course the progressbar is never going to change.
From what I can see from your question, everything should be working ok but I cant see that you have added Timer1.Interval = 1000 however you may have but this with the designer and not the coding side, however nevertheless here is how I did this project so you could see my working example just so you can be sure, If you have any problems let me know and i will do my best to help you out :)
Public Class Form1
Dim Timer1 As New Timer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Timer1.Enabled = True
Timer1.Interval = 1000
AddHandler Timer1.Tick, AddressOf Timer1_Tick
Timer1.Start()
End Sub
Private Sub Timer1_Tick()
Dim POWER As PowerStatus = SystemInformation.PowerStatus
Dim PERCENT As Single = POWER.BatteryLifePercent
Dim ONCHARGE As PowerStatus = SystemInformation.PowerStatus
ProgressBar1.Value = PERCENT * 100
Label1.Text = "Power Remaining: " & PERCENT * 100 & "%"
If ONCHARGE.PowerLineStatus = PowerLineStatus.Online Then
Label2.Text = "Currently: Charging"
Else
Label2.Text = "Currently: Not Charging"
End If
End Sub
End Class
I added a Progressbar and two labels to the form, one of which is the computer battery and another of which will tell the user if the cable is unplugged in or not, i know you didnt ask for the cable status but i added it just incase you needed it :)
Happy Coding

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

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

Variables to list box?

taking a VB class this term and I've been stumped on a problem I'm trying to figure out. We were asked to create a price calculator for movie titles at a movie rental place. Extra credit was storing them in a list and being able to print the list. I've gotten that far and now I want to go a step further and actually add titles to that list with an attached price. I figured the easiest way to do this would probably be with arrays but I don't have much experience working with arrays.
I was thinking something along the lines of storing each title(as its added) as well as the price in a variable to give a "Movie Title - $2.93" format in every line of the list box. For the sake of this problem I'm going to just post my full source code and that might make it easier to see what I'm trying to accomplish. ANY help would be MUCH appreciated. Thanks Stack overflow community!
A screenshot of my project can be viewed here: http://puu.sh/54SgI.jpg
Public Class Form1
'globablly declared because I might use them outside of btnAdd_Click event
Const decDiscount As Double = 0.9 '1-.10 discount = .9
Const decDVD As Decimal = 2D
Const decBlueray As Decimal = 2.5D
Const decDVDNew As Decimal = 3.25D
Const decBluerayNew As Decimal = 3.5D
Dim intCount As Integer
Dim decCost, decTotal As Decimal
Dim decDayTotal As Decimal
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AcceptButton = btnAdd
End Sub
Private Sub chkDiscount_Click(sender As Object, e As EventArgs) Handles chkDiscount.Click
If chkDiscount.CheckState = 1 Then
chkDiscount.Enabled = False
End If
End Sub
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
'Display error when no title entered
If txtAdd.Text = "" Then
MessageBox.Show("Please enter a movie title and select the appropriate item details.", "Complete details", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
listMovies.Items.Add(txtAdd.Text)
listMovies.SelectedIndex = listMovies.SelectedIndex + 1
End If
'update list
'clear txtbox
txtAdd.Text = ""
'Decision Statements to calculate correct price
If radDVD.Checked = True Then
decCost = CDec(decDVD.ToString("c"))
If chkNew.Checked = True Then
decCost = CDec(decDVDNew.ToString("c"))
End If
ElseIf radBlueray.Checked = True Then
decCost = CDec(decBlueray.ToString("c"))
If chkNew.Checked = True Then
decCost = CDec(decBlueray.ToString("c"))
End If
End If
If chkDiscount.Checked = True Then
decCost = CDec((decCost * decDiscount).ToString("c"))
End If
'display cost
txtCost.Text = CStr(CDec(decCost))
'calc total
decTotal = CDec(decTotal + decCost)
'display total
txtTotal.Text = CStr(CDec(decTotal))
'clear chkNew every item added to list
chkNew.CheckState = 0
End Sub
'Public so summary message box can access variable
Public Sub btnFinish_Click(sender As Object, e As EventArgs) Handles btnFinish.Click
'Add +1 to counter & update txtCounter
intCount = CInt(Val(intCount) + 1)
'add to day total
decDayTotal = CDec(Val(decDayTotal) + decTotal)
'Set Everything back to empty/enabled
chkDiscount.Enabled = True
chkDiscount.CheckState = 0
chkNew.CheckState = 0
txtAdd.Text = ""
txtCost.Text = ""
txtTotal.Text = ""
decTotal = 0
decCost = 0
'Instead of clearing radios each time, a more desirable result would be to have DVD always set back to the default checked radio
radDVD.Checked = True
radBlueray.Checked = False
listMovies.Items.Clear()
End Sub
Private Sub btnSummary_Click(sender As Object, e As EventArgs) Handles btnSummary.Click
If decTotal > 0 Then
MessageBox.Show("Please finish your current order before viewing a daily summary.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
MessageBox.Show(("Your total cutomer count is: " & intCount) + Environment.NewLine + ("Your total sales today is: $" & decDayTotal), "Daily Summary", MessageBoxButtons.OK)
End If
End Sub
Private Sub btnRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemove.Click
listMovies.Items.Remove(listMovies.SelectedItem)
End Sub
I wont go very far here because you need to do the work. But, I would start with a class:
Public Class Movie
Public Title As String = ""
Public Cost As Decimal
' prevents you from adding a movie without critical info
Public Sub New(ByVal t As String, ByVal c As Decimal)
Title = t
Cost = c
End Sub
End Class
This would hold the info on one movie title rental, and keep it together (and can be added to in order to print exactly as you showed) . The plan (to the extent I understand what you are after) would be to create one of these for each movie rented and add it to a List(Of Movie) this is more appropriate than a Dictionary in this case.
To create a movie:
Dim m As New Movie(theTitle, theCost)
Things I would do:
You did a good job of declaring numerics as numbers. Fix the code that converts it to string and back to numeric. (edit your post)
You can use the Movie Class to populate the "Shopping Cart" listbox alone; at which point, listMovies.Items would BE the extra credit List. But it wouldnt hurt to use/learn about List (Of T). (BTW, does 'print' mean to paper, on a printer?)
What are you doing with chkDiscount? If they check it, you disable it (and never enable). Did you mean to disable the New Releases check? In THAT case, arent they really a pair of radios too?
Either way, CheckChanged is a better event for evaluating and there is no reason to manually set the check state for the user that happens by itself.
Check out List(of T) and HTH
A good thing to think about when doing assignments like this (particularly when learning your first language) is to think of the algorithm (the step you need to get to your goal).
1st, determine all the steps you need to get to your goal.
2nd, and I think this is the more import point for your question, figure out what order the steps need to be in (or better yet, what order they are most efficient in).
In your case I think that you are kind of ice skating up hill by adding the name of the movie to the list first, and then trying to add the price to the line later. Unless that kind of functionality was requested as part of the assignment I would require the user to enter both the name AND the price before accepting either (just like you do with the name currently). Like thus:
If txtAdd.Text <> "" AND txtCost.Text <> "" Then 'requiring both fields to not be null
''add moive code
Else
''MessageBox.Show("Yadda Yadda Yadda")
End If
I agree with Plutonix that creating a class, while overkill in your case, is a good idea, as it will give you practice for when it WILL be appropriate. Once you have that a class of Movie, you can then create lists of Movie(s) like this:
Dim MovieList as new List(of Movie)
So then, each time you press the btnAdd button, you can pass the values to a movie AND add it to the list.
Dim m As Movie
Dim MovieList as new List(of Movie)
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
'Display error when no title entered
If txtAdd.Text <> "" And txtCost.Text <> "" Then
myMovie = New Movie(txtAdd.Text, txtCost.Text)
myMovieList.Add(myMovie)
listMovies.Items.Clear()
For Each X As Movie In myMovieList
listMovies.Items.Add(X.DisplayMovie)
Next
Else
MessageBox.Show("Please enter a movie title and select the appropriate item details.", "Complete details", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
'Other Code
End Sub
Note the line ListMovies.Items.Add(X.DisplayMovie) I added a function to the class Movie (seen below) so that it will do the formatting as you suggested.
Public Function DisplayMovie()
Return Title & " - $" & Cost
End Function
This will get you much of the way. Try to extrapolate what Plutonix and myself have explained to further refine your code. For instance, try encapsulating your adjusted price calculation in its own function so you can call it from anywhere.