Calculate the amount to pay based on time difference in 2 textboxes VB.Net - vb.net

enter image description here
I want to get the amount to pay based on time difference of the time in and time out.
example. Time In is : 7:00:00
Time Out is : 13:00:00
The difference is 6 hrs
and lets say that the per hour rate is 10.00, so the amount should be 60.00
thanks! im using vb.net
what im trying to do is like this.
Private Const Format As String = "HH:mm:ss"
'this is the code i used to get the time in
Private Sub btnTimeIn_Click(sender As Object, e As EventArgs) Handles btnTimeIn.Click
TextboxTimeIn.Text = DateTime.Now.ToString(Format)
End Sub
'this is the time out
Private Sub btnTimeOut_Click(sender As Object, e As EventArgs) Handles btnTimeOut.Click
TextboxTimeOut.Text = DateTime.Now.ToString(Format)
'this is what is use to get the time difference
txtAmount.Text = Convert.ToDateTime(TextboxTimeOut.Text).Subtract(Convert.ToDateTime(TextboxTimeIn.Text)).ToString()
End Sub
but instead of showing the time difference, i want to show the amount in the txtAmount. example
if timeDifference <= 60mins , then
txtAmount = 10
else timeDifference > 60mins , then
txtAmount = 20

You want to know 3 things:
How much time passed between checkin and checkout
How many hours is that
Hom much will this cost
These points could be calculated in only one line, but for the sake of clarity we'll clear them one by one:
'let's use some more variables to make this easier
Private Const Format As String = "HH:mm:ss"
Private checkin As DateTime
Private checkout As DateTime
Private rate As Integer = 10
'now with variables!
Private Sub btnTimeIn_Click(sender As Object, e As EventArgs) Handles btnTimeIn.Click
checkin = Now
TextboxTimeIn.Text = checkin.ToString(Format)
End Sub
Private Sub btnTimeOut_Click(sender As Object, e As EventArgs) Handles btnTimeOut.Click
checkout = Now
TextboxTimeOut.Text = checkout.ToString(Format)
'First we check for an amount of hours, then we add one if they overstayed
Dim timeStayed As Integer = checkout.Hour - checkin.Hour
If TimeStayed.Minute > 0 Then timeStayed += 1
'Notice the use of a variable so you can tweak your rates easily
txtAmount.Text = (timeStayed * rate).ToString
End Sub
What you need to remember here is:
Make things easier on you. Don't convert everything all the time.
Follow your own pseudocode. You already knew what to do. Do it.
I used Integers for money... this is bad! You should change this as soon as possible, so your numbers can have decimals! (also you should format the txtAmount as money)
Have fun!

Related

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

changing vb.net chart xAxis maximum and minimum datetime type

I am using chart control on vb.net windows form application.
I am loading data into chart1 and all looks good; I am using this data type:
Chart1.Series("test").XValueType = DataVisualization.Charting.ChartValueType.DateTime
Chart1.Series("test").YValueType = DataVisualization.Charting.ChartValueType.Int32
Then I am using a Trackbar1 control to change/zoom/rescale xAxis and using this code:
Private Sub TrackBar1_Scroll(sender As Object, e As EventArgs) Handles TrackBar1.Scroll
ChartRanger(TrackBar1.Value)
End Sub
Having TrackBar1 min=0 and max=366 in Property window.
While the ChartRanger function looks like this:
Private Sub ChartRanger(theDays As Integer)
Chart1.ChartAreas(0).AxisX.IntervalType = 0
Chart1.ChartAreas(0).AxisX.Interval = 0
Chart1.ChartAreas(0).AxisX.Minimum = 0
Chart1.ChartAreas(0).AxisX.Maximum = theDays
End Sub
There is no debugging error and it looks like working; but the logic is not correct in the output.
i.e. What I am trying to achieve is to let app user define minimum datetime and maximum datetime for chart1 xAxis. having dataset contains a daily records.
Update: I have seen the other related posts, they suggest answers for ASP, VBA but can't find answer for VB.Net win forms; its more for the best logic here.
I think your problem is Chart1.ChartAreas(0).AxisX.Maximum = theDays. The AxisX type is a Double representing a DateTime, while theDays is an Integer. You need to figure out what the maximum date for AxisX should be based on the value of theDays, and convert that date to a double using ToOADate().
Here's a working example:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Chart1.Series.Clear()
Dim s = Chart1.Series.Add("s")
s.ChartType = DataVisualization.Charting.SeriesChartType.Point
s.XValueType = DataVisualization.Charting.ChartValueType.DateTime
s.XValueType = DataVisualization.Charting.ChartValueType.Int32
For i As Integer = 0 To 100
s.Points.AddXY(Date.Today.AddDays(i), i)
Next
TrackBar1.Maximum = 100
End Sub
Private Sub TrackBar1_Scroll(sender As Object, e As EventArgs) Handles TrackBar1.Scroll
Dim val As Integer = TrackBar1.Value
Chart1.ChartAreas(0).AxisX.Maximum = Date.Today.AddDays(val).ToOADate()
End Sub
End Class
Or if you don't know the min and max dates already, you can set the axis maximum relative to the position of the TrackBar:
Private Sub TrackBar1_Scroll(sender As Object, e As EventArgs) Handles TrackBar1.Scroll
' Get min and max dates
Dim maxDate As Date = Date.FromOADate(Chart1.Series("s").Points.FindMaxByValue("X").XValue)
Dim minDate As Date = Date.FromOADate(Chart1.Series("s").Points.FindMinByValue("X").XValue)
' Get total days between dates
Dim totalDays = maxDate.Subtract(minDate).Days
' Get the bar position as a percent of 100
Dim barPct As Double = TrackBar1.Value / TrackBar1.Maximum
' Find the maximum day that should be displayed on the plot
Dim maxAxisDay As Integer = barPct * totalDays
' Get the date of the maximum day
Dim maxAxisDate = minDate.AddDays(maxAxisDay)
' Set maximum. Convert the date to a double using .ToOADate()
Chart1.ChartAreas(0).AxisX.Maximum = maxAxisDate.ToOADate()
End Sub
Edit:
Assuming that the trackbar maximum is set to the total number of days represented by the dataset, it's a bit easier:
Private Sub TrackBar1_Scroll_1(sender As Object, e As EventArgs) Handles TrackBar1.Scroll
' Get the first date
Dim minDate As Date = Date.FromOADate(Chart1.Series("s").Points.FindMinByValue("X").XValue)
' Assuming that the trackbar has the total number of days represented, the maximum date to display is the first date plus the
' days represented by the trackbar
Dim maxDisplayDate As Date = minDate.AddDays(TrackBar1.Value)
' Set the max axis
Chart1.ChartAreas(0).AxisX.Maximum = maxDisplayDate.ToOADate()
End Sub

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

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