Procedure comparing dates in vb.net doesn't appear to do anything - vb.net

Pretty much just the title, I've been learning vb for my computer science A-level and ran into some trouble with this exercise. I made a procedure to affect the final cost of an invoice by comparing the current date to the due date, but the due date that I input does not seem to have any effect on the final cost.
Form:
Invoice Form
Task:
Write a program that processes invoices for a company selling a variety of products. Ask the user to enter the unit cost of the product, how many were sold and the date the invoice had to be paid by. A check box should be used to indicate if the product is VAT rated. When these details have been entered the user should click a button. This event should call two general procedures. The first should calculate and return the basic cost of the invoice, including VAT. The second should reduce the basic cost by 10% if the invoice has been paid on time. The final cost should be displayed by the Click event of the button.
Code:
Public Class Form1
Dim invoice As Integer
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim unitCost As Integer = txtCost.Text 'Input cost of product in textbox
Dim unitsSold As Integer = txtUnits.Text 'Input units sold in textbox
Dim dueDate As Date = dtpDueDate.Value 'Input date in date and time picker
Dim VATCheck As Boolean = chkVAT.Checked 'Input VAT rating in checkbox
Call InvoiceProcess(unitCost, unitsSold, VATCheck)
Call DueCheck(dueDate, invoice)
MsgBox(invoice)
End Sub
Sub InvoiceProcess(ByRef price As Integer, ByRef units As Integer, ByRef VAT As Boolean)
If VAT = True Then
invoice = 1.2 * price * units
Else
invoice = price * units
End If
End Sub
Sub DueCheck(ByRef dateDue As Date, ByVal invoice As Integer)
Dim todayDate As Date = Today.Date 'Current date
Dim overDue As Integer = DateTime.Compare(todayDate, dateDue.Date)
If overDue <= 0 Then
invoice = invoice * 0.9
End If
End Sub
End Class

The question says "This event should call two general procedures. The first should calculate and return..." - notice it says "return" - that means that it needs to be a function, not a sub.
Once you've got that fixed, the invoice value can be passed from one method to another in the parameters, so you can remove the Dim invoice As Integer from where it is because it is currently scoped to entire class, which you probably don't want.
Also, invoice should be a Decimal, not an Integer.

Related

Calculated textbox does not calculate if Unit Price is formatted as Currency

Simple calculation TotalPrice = QTY * UnitPrice
Does not calculate when I get the Unit Price to display as currency.
The unit price is retrieved from a combo box in the AfterUpdate event as follows:
Private Sub cboItemRequested_AfterUpdate()
' 0 1 2 3 4 5 6
' ITEM Category SIZE UI PRICE NSN_ORDER UNIT_PACK
With Me
.txtDescrOfItemRequested = .cboItemRequested
.txtUI = .cboItemRequested.Column(3)
.txtQTY = 1
.txtUnitPrice = Format(.cboItemRequested.Column(4), "Currency")
.txtPartNumNSN = .cboItemRequested.Column(5)
End With
End Sub
Even though the combo box displays the currency correctly in the 4th column, it does not populate the Unit Price txtbox correctly unless I apply the Format(XXXXX, "Currency"). Incidentally, the textbox is also formatted as currency. However, when I do get the dollar sign to appear, the final calculation TotalPrice remains zero.
I even applied the following to the txtTotalPrice
=Val(Nz([txtQTY],0))*Val(Nz([txtUnitPrice],0))
I tried responding to #krish KM so I scrapped everything above and instead created this function:
Public Function cTotalPrice(vQTY As Variant, vUnitPrice As Variant) As Currency
'only return a value if both fields are numeric
If IsNumeric(vQTY) = True And IsNumeric(vUnitPrice) = True Then
cTotalPrice = vQTY * vUnitPrice
End If
End Function
which I only call like this the AfterUpdate event of the cboItemRequested box and any time txtQTY or txtUnitPrice are updated
.txtTotalPrice = cTotalPrice(.txtQTY, .txtUnitPrice)
But txtUnitPrice simply does not display as currency even with txtUnitPrice formatted as currency.
SOLUTION:
I needed to Format the txtUnitPrice with VBA
.txtUnitPrice = Format(.cboItemRequested.Column(4), "Currency")
Yes, the txtBoxPrice formatted as currency just ignores it for some reason.
But in order for the TotalPrice to come out right, it was necessary to recalulate it at the end. This was the first tip I was given. Thanks krish KM

How can I calculate the cost of the Loan with the Capital and interest rate? Vba

I’m doing a Intership as a Developer an got a tough exercise. I’ve got a Loan Text and there are 3 Fields blank, the Loan, the Capital and the interest rate. I’ve created already the and it look like this:
Private Sub l_jahre_Click()
End Sub
Private Sub txt_abtrag_Change()
CalculateFormular
End Sub
Private Sub txt_darlehen_Change()
CalculateFormular
End Sub
Private Sub txt_zinssatz_Change()
CalculateFormular
End Sub
Private Sub CalculateFormular()
If (validate()) Then
Debug.Print "Success"
End If
End Sub
Private Function validate() As Boolean
validate = True
On Error GoTo x
a = CDbl(txt_abtrag.Value) + CDbl(txt_darlehen.Value) + CDbl(txt_zinssatz.Value)
Exit Function
x:
validate = False
End Function
Public Sub test2()
'Debug.Print txt_zinssatz.Value
l_zinsen.Caption = "inf."
End Sub
Don’t mind the Value of them xd
And now I Need to calculate, like I said, the cost of the Loan with the Capital and interest rate.
I Need to fill it up and it Looks like this.
Public Function GetTotalCost(ByVal capital As Double, ByVal rate As Double) As Double
GetTotalCost = 0
End Function
Public Function GetRentTime(ByVal capital As Double, ByVal rate As Double, ByVal monthPay As Double) As Double
GetRentTime = 0
End Function
please don’t say the full Code or the full answer I just Need some help to understand and what method I should use.
Thank you for your help.
The financial formulae below each solve one financial argument (PV, FV, PMT, NPER) in terms of the others, using (pmt*nper)+pv+fv = 0 if the rate is 0, and pv*((1+rate)^nper)+pmt*(1+rate*type)*((1+rate)^nper-1)/rate+fv = 0 otherwise, where:
• pv is the present value of a loan or investment, and represents the current value of a series of future payments. For example, when you borrow money, the amount you owe is the present value to the lender.
• fv is the future value, or a cash balance of the loan or investment after the last payment is made.
• rate is the interest rate per period.
• nper is the total number of payment periods over the life of the loan or investment.
• pmt is the fixed instalment paid in each period. The instalment amount usually includes components to cover both principal and interest but may not include loan fees etc. This is negative if you're borrowing, because it represents money you would pay (i.e. a negative cash flow).
• type is the number 0 or 1 and indicates when instalments are paid. 0 indicates payments are made at the end of the period, 1 indicates payments are made at the start of the period. Equally, some loans charge interest on the basis of the amount outstanding at the beginning of the period, whilst others charge interest on the basis of the amount outstanding at the end of the period.
Solving for the future value, the formula is:
fv=-if(rate=0,pmt*nper+pv,(pv*((1+rate)^nper)+pmt*(1+rate*type)*((1+rate)^nper-1)/rate))
Solving for the present value, the formula is:
pv=-if(rate=0,pmt*nper+fv,(fv+pmt*(1+rate*type)*((1+rate)^nper-1)/rate)/((1+rate)^nper))
Solving for the payment value, the formula is:
pmt=-if(rate=0,(pv+fv)/nper,(pv*((1+rate)^nper)+fv)/((1+rate*type)*((1+rate)^nper-1)/rate))
Solving for the number of periods, the formula is:
nper=-if(rate=0,(pv+fv)/pmt,(log(1+(pv+pmt*type)/pmt*rate)-log(1+(fv+pmt*type)/pmt*rate))/log(1+rate))
Solving for the interest rate, the formula is:
rate=(fv/pv)^(1/nper)-1
provided pmt is 0. Otherwise, you can only solve for the interest rate through iteration (eg using one of the above formulae).

Multiplying multiple texboxes

I am creating a menu application, I have at the moment 3 textboxes, textbox1 is price, textbox2 is quantity and textbox3 is total. I have successfully written the code to calculate the price of an item depending on the quantity they need. The code i have right now:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
TextBox8.Text = CStr(Val(TextBox6.Text) * Val(TextBox7.Text))
End Sub
Now what I need is that I will have more items say 10 along with textboxes beside as quantity which makes 20 textboxes and one total textbox. How can I write the code so that it calculates every textbox as well as null values say if out of the 10 items i want only 2 items 1 per quantity into the total value.
Thanks
First, i strongly suggest to use .NET methods instead of old VB methods. I also would set OPTION STRICT to On in general which avoids "magical" conversions done for you by the runtime. Instead you have to specify the correct types which is a good thing since it can prevent errors on runtime and it also helps to learn the .NET types and methods.
I would add those TextBoxes all to the same container-control (like a Panel or something similar). I also suggest to use more meaningful names for your controls(f.e. TxtTotal for the total-textbox).
So if all price-textboxes' names start with TxtPrice (f.e. TxtPrice1 etc) and all quantity-TextBoxes start with TxtQuantity (f.e. TxtQuantity1 etc), this LINQ query approach will work:
Dim allTextBoxes = PriceQuantityPanel.Controls.OfType(Of TextBox)()
Dim allPrices = From txt In allTextBoxes
Where txt.Name.StartsWith("TxtPrice")
Dim allQuantities = From txt In allTextBoxes
Where txt.Name.StartsWith("TxtQuantity")
Dim price As Decimal
Dim invalidPrices = From txt In allPrices
Where Not Decimal.TryParse(txt.Text, price)
If invalidPrices.Any() Then
MessageBox.Show("Please enter valid prices(Decimal)!")
Return
End If
Dim quantity As Int32
Dim invalidQuantities = From txt In allQuantities
Where Not Int32.TryParse(txt.Text, quantity)
If invalidQuantities.Any() Then
MessageBox.Show("Please enter valid quantities(Integer)!")
Return
End If
Now you can "join" the pairs of price and quantity textboxes by the number-suffix:
Dim query = From txtP In allPrices
Join txtQ In allQuantities
On txtP.Name.Substring("TxtPrice".Length) Equals txtQ.Name.Substring("TxtQuantity".Length)
Select New With {.Price = Decimal.Parse(txtP.Text), .Quantity = Int32.Parse(txtQ.Text)}
Dim totalSum As Decimal = query.Sum(Function(x) x.Price * x.Quantity)
TxtTotal.Text = totalSum.ToString()

Displaying "amount paid" was not enough on Change Calculator, VB VS2012

I am new to VB and for a class project we are to make a change calculator, similar to the one that a question was asked on here before. I have an amount owed and amount paid label and textbox. If the amount owned is greater than the amount paid, the program should display message to remind the customer and tell them how much more to pay.
I figured it out, but the amount that is still due that is displayed in the message is -1.
Example:
Amount Owed: 25
Amount Paid:10
The message will read, The amount paid is less than what is owed. Please pay $ -1 more.
I'm not sure what I've done wrong, and I'm stuck. Any help will be appreciated!
Option Strict On
Option Explicit On
Public Class Form1
Dim AmountPaid As Double
Dim AmountOwed As Double
Private Sub CalculateButton_Click(sender As Object, e As EventArgs) Handles CalculateButton.Click
'input amount owed from OwedMaskedTextBox
'input paid amount from PaidTextBox
AmountOwed = Convert.ToDouble(OwedTextBox.Text)
AmountPaid = Convert.ToDouble(PaidTextBox.Text)
'calculate difference of amount owed and paid
'display an alert message if paid amount is less than what is owed
Dim dif As Double
Dim result As Double = 0
result = CDbl(AmountPaid < AmountOwed)
dif = AmountPaid - AmountOwed
If CBool(result) Then
AlertLabel.Text = "Amount paid is less than what is owed." &
"Please pay $ " & result & " more."
Else
AlertLabel.Text = ""
End If
'display the result
'let totallabel change text to display the difference
TotalLabel.Text = "Change: " &
dif.ToString()
End Sub
End Class
Change the code in this way
'calculate difference of amount owed and paid
'display an alert message if paid amount is less than what is owed
Dim result As Boolean
result = (AmountPaid < AmountOwed)
dif = AmountPaid - AmountOwed
If result Then
.....
The expression (AmountPaid < AmountOwed) is a boolean expression and you could assign directly to a boolean variable. Then you could test this boolean before displaying your message.
So there is no need of these conversions that introduce errors.

Visual Basic: Making multiple forms for an order

I've been working on this project for two weeks now and I'm drained from all the hiccups I've come across. Now I've hit a brick wall.
I'm making a "simple" order form in Visual Basic 2010 that calculates the amount due for an order and then from the total determines what the shipping will be. I've been able to accomplish the following tasks:
accept customer data (name, address, city, state abbreviation, zipcode)
calculate total with shipping costs (accurately, for the most part)
clear the order form and exit
But the way I have it right now, a customer can only put in 1 order form.
Problem: I have to figure out a way to allow a customer to place an order form for multiple items. (I'll assume that a customer will not place an order for more than 20 items). So what would be the best way to go about saving the information for multiple items then calculating the cost at the end?
If it's multiple form creation, how is that done? Is the keyword "Container" the way to go, and how? At the end of the day, I just don't know how to create this multiple item form (it's like a database in Visual Basic), so any method, at least pointing me in the right direction, would be helpful.
(Tried to post an image of my work so far but I'm new here - can't post images yet. I've posted a bit of my code below - code works for 1 order)
Snippet Code:
Private Sub total_mouseleave(ByVal sender As Object, ByVal e As EventArgs) Handles total.MouseLeave
Dim gs_1 As Decimal = 4.95
Dim gs_2 As Decimal = 6.95
Dim gs_3 As Decimal = 8.95
Dim gs_4 As Decimal = 10.95
Dim gs_5 As Decimal = 12.95
Dim ex_1 As Decimal = 14.95
Dim ex_2 As Decimal = 16.95
Dim ex_3 As Decimal = 18.95
Dim ex_4 As Decimal = 20.95
Dim ex_5 As Decimal = 22.95
Dim totalcost As Decimal
totalcost = Convert.ToDecimal(total.Text)
If gs_radiobutton.Checked Then
If (totalcost < 1) Then
total.Text = Val(0)
shipping.Text = Val(0)
ElseIf (1 < totalcost AndAlso totalcost < 15) Then
total.Text = Val(totalcost + gs_1)
shipping.Text = ground_1
ElseIf (15 < totalcost AndAlso totalcost <= 49.99) Then
total.Text = totalcost + gs_2
shipping.Text = gs_2
ElseIf (50 < totalcost AndAlso totalcost <= 99.99) Then
total.Text = totalcost + g_3
shipping.Text = gs_3
ElseIf (100 < totalcost AndAlso totalcost <= 199.99) Then
total.Text = totalcost + gs_4
shipping.Text = gs_4
Else
total.Text = totalcost + gs_5
shipping.Text = gs_5
End If
End If
'// . . . .
End Sub
It's not clear from your post if you mean order forms as in a Form object within VB or an order placed by the user.
If you meant orders placed by the user then it would be simpler to use a single form but create a few custom classes to hold all the order line details:
' Class used for each order line
Public Class orderline
Public Value As Decimal
Public StockID As Integer
Public Qty As Integer
End Class
' Class used to store the entire order
Public Class Order
' List of orderlines (similar to an array)
Public OrderLines As List(Of orderline)
Private _totalcost As Decimal
Public ReadOnly Property TotalCost As Decimal
Get
Dim t As Decimal
For Each l In OrderLines
t = t + (l.Value * l.Qty)
Next
Return t
End Get
End Property
End Class
Then in the form you can use the classes as below:
Public Class Form1
Dim ord1 As New Order
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
TextBox1.Text = ord1.TotalCost
End Sub
End Class
You can then create more than one order stored on the form using a list:
Dim CustomerOrders as List<Of Order>
You should be able to create multiple instances of a form and show them non-morally. Whether this is the best design is another discussion.
The non-modal forms would all be visible and can be 'owned' by a main form.
Try something like this:
Dim firstInstance As New YourForm()
Dim secondInstance As New YourForm()
firstInstance.Show() 'Not ShowDialog()
secondInstance.Show(myParent) 'Optional parent form parameter
You'll need to watch the scope of your form instances as the forms will be closed if the variables go out of scope.
This may not be the ultimate solution, but it's something you can try on the way to finding the optimal approach.
Considering the latest comment:
The problem is not clear. Do you want to create multiple forms, one form per order? Or do you want one form that can show multiple orders?
My solution will allow you to show multiple forms while the other answer posted suggests a neat solution to creating one form with multiple orders.
Personally, I would create a single form that shows multiple orders, ListView maybe, that provides some way of viewing/editing each order's details and then allowing the orders to be submitted in a batch. It's more complex but would be more usable, IMHO.