locked
VB code for total price RRS feed

  • Question

  • I need to write a code that would allow users to enter a quantity, and cost. then have it calculate the price.

    but my calculation is wrong. Im new to this but this is what I have and its not working.

    ublic Class frmmain
        Private frmmain As Decimal

        Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
            Dim decPrice(9) As Double
            Dim txtQuantity As Integer


            txtTotal = decPrice * txtQuantity


        End Sub

        Private Sub txtTotal_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtTotal.TextChanged
            Dim txtQuantity As Integer
            Dim decPrice As Integer
            txtTotal = txtQuantity * decPrice(10)
        End Sub

    Monday, October 15, 2012 3:24 AM

Answers

  • Create a program that allows users to enter an item code, a quantity, and a cost
    per item for an order and outputs the total for the order. You need to:
    • Write the declaration for the data structures you will use to store the data.

    Unfortunately, your task list has left out the logical starting point, which is to design a form in a way that allows those procedures to be carried out.

    The user needs to enter an item code, a quantity and a cost.  So you will need a text box for each of those. These will be txtItem, txtQuantity and txtPrice.  You could also have a text box to dsplay a total - txtTotal.

    If the user is going to do this up to ten times you need a button for the user to say "here is the information for one item".  It does what I think yo are trying to do witht he TextChanged event.  This is btnCalculate.   You should also let the user know what they have done so far - I would recommend a list box - ListBox1 in this example.  You also might need a button for the user to say "That's the end of the order" (although you could display a continuous update (as in this example), so there's no need for that).

    You will need a structure for each line of the order.  I assume you have done structures already, although your instructions might have used that term somewhat loosely.  A structure for the order line looks like this:

        Private Structure OrderLine
            Dim LineItem As String
            Dim LineQuantity As Integer
            Dim LinePrice As Decimal
    
            Public Sub New(ByVal Item As String, ByVal Quantity As Integer, ByVal Price As Decimal)
                LineItem = Item
                LineQuantity = Quantity
                LinePrice = Price
            End Sub
    
            Public Overloads Function ToString() As String
                Return LineItem & " " & LinePrice.ToString _
                                & " " & LineQuantity.ToString _
                                & " " & (LinePrice * CDec(LineQuantity)).ToString
            End Function
    
        End Structure

    Note how I have declared a constructor (the New sub) for the structure, and a ToString.  These aren't strictly needed, but they are included here to show how using a structure can simplify your code.

    Now you need to get the user input.  This happens in the button click event for the ""here is the information for one item" button.  The item code is simply a string, so it's easy. The others must be checked to ensure they are valid. The whole thing looks like this:

    Option Strict On
    Public Class Form1
        Dim OrderLines As List(Of OrderLine) = New List(Of OrderLine)
    
        Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
            Dim intQuantity As Integer
            If Not Integer.TryParse(txtQuantity.Text, intQuantity) Then
                MsgBox("Error in entering quantity")
                Exit Sub
            End If
            Dim decPrice As Decimal
            If Not Decimal.TryParse(txtPrice.Text, decPrice) Then
                MsgBox("Error in entering price")
                Exit Sub
            End If
    
            Dim decTotal As Decimal = decPrice * CDec(intQuantity)
            txtTotal.Text = decTotal.ToString
    
            OrderLines.Add(New OrderLine(txtItem.Text, intQuantity, decPrice))
            ListUpdate()
        End Sub
    
        Private Sub ListUpdate()
            ListBox1.Items.Clear()
            For Each O As OrderLine In OrderLines
                ListBox1.Items.Add(O.ToString)
            Next
        End Sub
    
        Private Structure OrderLine
            Dim LineItem As String
            Dim LineQuantity As Integer
            Dim LinePrice As Decimal
    
            Public Sub New(ByVal Item As String, ByVal Quantity As Integer, ByVal Price As Decimal)
                LineItem = Item
                LineQuantity = Quantity
                LinePrice = Price
            End Sub
    
            Public Overloads Function ToString() As String
                Return LineItem & " " & LinePrice.ToString _
                                & " " & LineQuantity.ToString _
                                & " " & (LinePrice * CDec(LineQuantity)).ToString
            End Function
       End Structure
    End Class

    Note the list is used for the order lines.  Note also how the ToString method of the structure is used to desplay each order line int eh list.  You must look up the TryParse method in the online help so you can see what this statement is doing and how it works.

    • Write the code you will use to input the data. Assume that you are getting
    the data from TextBox controls.

    That's very poor expression - you do not input the data.  You put code in the button click event (as above) to get the data that the user has already input.  'Input' as used here must mean "create an order line data structure, and populate it with the data input by the user".

    • Allow the user to enter up to 10 different items.

    Not done in this example.  You need to add code to check the size of the list to see if the user has exceeded the limit. Note that this part of the assignment might have been included because there was an assumption that you would use arrays (some of these exercises are very old).  As you are using a List instead of arrays then there is no need for such a restriction.

    • Write the code for determining the order total.

    The total for each line is done for the txtTotal textbox, and also in the ToString method of the structure. A useful extra-credit exercise is to create a method in the structure that returns the total for you, so you are not doing the calculation in two different places.

    To create the order total you need to iterate through your list of order lines, accumulating the line totals.  That could be done in the ListUpdate method.

    • Edited by Acamar Saturday, October 20, 2012 1:13 AM sp
    • Proposed as answer by Frank L. Smith Saturday, October 20, 2012 1:23 AM
    • Marked as answer by Mark Liu-lxf Tuesday, October 23, 2012 8:18 AM
    Saturday, October 20, 2012 1:03 AM

All replies

  • I need to write a code that would allow users to enter a quantity, and cost. then have it calculate the price.

    but my calculation is wrong. Im new to this but this is what I have and its not working.

    ublic Class frmmain
        Private frmmain As Decimal

        Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
            Dim decPrice(9) As Double
            Dim txtQuantity As Integer


            txtTotal = decPrice * txtQuantity


        End Sub

        Private Sub txtTotal_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtTotal.TextChanged
            Dim txtQuantity As Integer
            Dim decPrice As Integer
            txtTotal = txtQuantity * decPrice(10)
        End Sub

    OK, a couple of things:

    1. don't have a variable with the same name as your Form (and what is the purpose of the Decimal variable frmmain - I don't see it used anywhere?)

    2. don't do this in the TextBox TextChanged event (meaning: delete that code); use the Button click event

    3. why is decPrice an array? I think you want to remove all the (x) instances

    4. the variable txtQuantity should be renamed intQuantity

    5. where are the values for txtQuantity and decPrice coming from? As it is, these variables are not given any value (other than the default value)

    6. I'm sure txtTotal is a reference to a TextBox. You need to set a Property of the TextBox to the decPrice*txtQuantity, not the TextBox itself.

    Make these changes and then post back with any other problems

    Edit: One more thing. Go to Tools >> Options >> Projects and Solutions >> VB Defaults. Set Option Strict and Option Explicit to On, then click OK

    “This forum post is my own opinion and does not necessarily reflect the opinion or view of Microsoft, its employees, or other MVPs.”


    • Edited by jwavila Monday, October 15, 2012 5:07 AM
    • Proposed as answer by Cor Ligthert Monday, October 15, 2012 9:06 AM
    Monday, October 15, 2012 4:27 AM
  • can you explain how to set the property in number 6.

    also what i am trying to do is once the code is set, the user will enter the price in one textbox and the quantity in the other textbox. when they click total it will multiple the two boxes and output the answer

    Tuesday, October 16, 2012 7:51 PM
  • can you explain how to set the property in number 6.

    also what i am trying to do is once the code is set, the user will enter the price in one textbox and the quantity in the other textbox. when they click total it will multiple the two boxes and output the answer

    I'll let jwavila speak for himself, but consider this: A TextBox displays text (only text) using one of its properties. Which property of a TextBox would you use to have it display some string?

    Your input is via TextBoxes which is fairly common, but you do need to understand the risks (and then work out a way to overcome the issues). What do you suppose would happen if, rather than a user entering a number, they typed in a word?

    Would that pose a problem? If so, how might you go about taking care of that problem?

    Of course someone here could write a few lines of code and you copy it and off you go - but I would challenge you to think through these things and let's see if you can learn a bit about the whole process in the doing! ;-)

    Good luck on your project. :)


    Please call me Frank :)

    Tuesday, October 16, 2012 10:10 PM
  • so then should I then just use Dec, or Str? I dont know where in the textbox property window i would make changes. I honesty do not understand codes at all. I am taking a class and got stuck on the assingment. my teacher is not much help. I understand that I need to do

    decPrice * txtQunantity= txtTotal or something like that.  I made some changes so now it looks like this.

    Public Class Cost

    End Class

    Private Sub Cost_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim decCost As Decimal
        For intCounter = 0 To 9
            decCost(intCounter) = -1.0
        Next
    End Sub

    Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
        Dim intCounter As Integer
        Dim intNumPrices As Integer
        Dim decCost
        Dim lstCost
        intNumPrices = decCost.GetUpperBound
        For intCounter = 0 To intNumPrices
            lstCost.Items.Add(decCost(intCounter))
        Next


        Dim txtCost As Integer = 0
        Dim intQuantity As Integer = 0
        Dim txtTotal As Integer

        txtTotal = txtCost * txtQuantity

    End Sub
    Tuesday, October 16, 2012 10:34 PM
  • lydiemab,

    First of all, I don't think anyone was aware that this is homework and as sort of an unspoken policy here, we don't do someone's homework for them. Point in the right direction, sure, but "do it for them", no. That's not to say that everyone here abides by that though!

    Moving forward though, what is the array for? What does that represent?

    As for the TextBox, answer this and you'll have answered the question about which property to use:

    Let's say I have a string variable as follows:

    Dim myString as String = "My String"

    Show me how you would show that string in TextBox1 please?


    Please call me Frank :)


    Tuesday, October 16, 2012 10:41 PM
  • I did an array cause  figured that was the only way to calculate price and quantity. the person can enter up to 10 different prices.

    Private Sub txtBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Txtbox1.TextChanged
          Dim myString as String = "My String"   

         For intcounter = ""

    Next

        End Sub
    End Class

    Tuesday, October 16, 2012 11:18 PM
  • I did an array cause  figured that was the only way to calculate price and quantity. the person can enter up to 10 different prices.

    Private Sub txtBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Txtbox1.TextChanged
          Dim myString as String = "My String"   

         For intcounter = ""

    Next

        End Sub
    End Class

    Ten different prices?

    I'm not following what you mean by ten different prices. You might want to type out what the assignment was.

    If you want to show text in a TextBox (named TextBox1), you would do it thusly:

    Dim myString As String = "My String"
    TextBox1.Text = myString

    Does that make sense? Let's not move forward until you understand that, but the next part that I'd like to ask you is how to show a number in a TextBox because remember - a TextBox is a control which is designed to show (and optionally alter) text. TEXT ONLY!

    Does that make sense as to how you'd show a string in a TextBox though?


    Please call me Frank :)


    • Edited by Frank L. Smith Tuesday, October 16, 2012 11:27 PM ...another typo dammit - it's been a long two days...
    Tuesday, October 16, 2012 11:25 PM
  • lydiemab,

    I'm taking off for the night (I might pop back in again several hours from now, but probably not).

    I'll look in again in about twelve hours or so.

    Hang in there - I'm sure it seems confusing at it was for everyone at first, but I promise you that you CAN do this and you CAN understand it. Just don't stop - don't throw your hands up in frustration and quit.

    So if you're willing to keep going, then you'll end up answering your own question and, in the process, understand it.

    Be well and I'll be back again soon.

    :)


    Please call me Frank :)

    Tuesday, October 16, 2012 11:58 PM
  • Let me try to add also something, 

    In this part of the code are at least 6 misunderstanding in your code

    txtTotal = txtQuantity * decPrice(10)
     
      • First of all you have called that variable txt............... which is misleading. By convention txt means always string. So that is what most of us think. But it is an integer. So simply calling it "quantity" and "total" clears a lot of your errors. (starting with a lower case because you declared it in the method.
      • Then you start with declaring it and then use it, that is vintage, declare it direct where you need it if it is not enclosed in a block of code (that is for instance inside an if block). 
      • You use the type integer and double, while decimal has to be used. Use never double for business solutions, it is for scientific use.
      • You create an array of 10 items, and uses the 11th not so clever (not even that strange VB  extra item for an thingy does not fit here)
      • It seems to be a business operation, but you have not told to round, therefore banking rounding is used, which I've never seen used outside banking. (For a strange reason Microsoft took that as default). Use Midway rounding away from zero. 
      • At a certain moment you have to set the decimal to a for users readable text. In past was for that used often the format, but currently the overloaded tostring function.

    rounding

    http://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx

    ToString, be aware there are 4 posibilities which have also some presets

    http://msdn.microsoft.com/en-us/library/system.decimal.tostring.aspx


    Success
    Cor

    Wednesday, October 17, 2012 6:36 AM
  • Here is the assingment, maybe I just dont understand what Im suppose to do.

    Create a program that allows users to enter an item code, a quantity, and a cost
    per item for an order and outputs the total for the order. You need to:
    • Write the declaration for the data structures you will use to store the data.
    • Write the code you will use to input the data. Assume that you are getting
    the data from TextBox controls.
    • Allow the user to enter up to 10 different items.
    • Write the code for determining the order total.

    Friday, October 19, 2012 9:52 PM
  • Create a program that allows users to enter an item code, a quantity, and a cost
    per item for an order and outputs the total for the order. You need to:
    • Write the declaration for the data structures you will use to store the data.

    Unfortunately, your task list has left out the logical starting point, which is to design a form in a way that allows those procedures to be carried out.

    The user needs to enter an item code, a quantity and a cost.  So you will need a text box for each of those. These will be txtItem, txtQuantity and txtPrice.  You could also have a text box to dsplay a total - txtTotal.

    If the user is going to do this up to ten times you need a button for the user to say "here is the information for one item".  It does what I think yo are trying to do witht he TextChanged event.  This is btnCalculate.   You should also let the user know what they have done so far - I would recommend a list box - ListBox1 in this example.  You also might need a button for the user to say "That's the end of the order" (although you could display a continuous update (as in this example), so there's no need for that).

    You will need a structure for each line of the order.  I assume you have done structures already, although your instructions might have used that term somewhat loosely.  A structure for the order line looks like this:

        Private Structure OrderLine
            Dim LineItem As String
            Dim LineQuantity As Integer
            Dim LinePrice As Decimal
    
            Public Sub New(ByVal Item As String, ByVal Quantity As Integer, ByVal Price As Decimal)
                LineItem = Item
                LineQuantity = Quantity
                LinePrice = Price
            End Sub
    
            Public Overloads Function ToString() As String
                Return LineItem & " " & LinePrice.ToString _
                                & " " & LineQuantity.ToString _
                                & " " & (LinePrice * CDec(LineQuantity)).ToString
            End Function
    
        End Structure

    Note how I have declared a constructor (the New sub) for the structure, and a ToString.  These aren't strictly needed, but they are included here to show how using a structure can simplify your code.

    Now you need to get the user input.  This happens in the button click event for the ""here is the information for one item" button.  The item code is simply a string, so it's easy. The others must be checked to ensure they are valid. The whole thing looks like this:

    Option Strict On
    Public Class Form1
        Dim OrderLines As List(Of OrderLine) = New List(Of OrderLine)
    
        Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
            Dim intQuantity As Integer
            If Not Integer.TryParse(txtQuantity.Text, intQuantity) Then
                MsgBox("Error in entering quantity")
                Exit Sub
            End If
            Dim decPrice As Decimal
            If Not Decimal.TryParse(txtPrice.Text, decPrice) Then
                MsgBox("Error in entering price")
                Exit Sub
            End If
    
            Dim decTotal As Decimal = decPrice * CDec(intQuantity)
            txtTotal.Text = decTotal.ToString
    
            OrderLines.Add(New OrderLine(txtItem.Text, intQuantity, decPrice))
            ListUpdate()
        End Sub
    
        Private Sub ListUpdate()
            ListBox1.Items.Clear()
            For Each O As OrderLine In OrderLines
                ListBox1.Items.Add(O.ToString)
            Next
        End Sub
    
        Private Structure OrderLine
            Dim LineItem As String
            Dim LineQuantity As Integer
            Dim LinePrice As Decimal
    
            Public Sub New(ByVal Item As String, ByVal Quantity As Integer, ByVal Price As Decimal)
                LineItem = Item
                LineQuantity = Quantity
                LinePrice = Price
            End Sub
    
            Public Overloads Function ToString() As String
                Return LineItem & " " & LinePrice.ToString _
                                & " " & LineQuantity.ToString _
                                & " " & (LinePrice * CDec(LineQuantity)).ToString
            End Function
       End Structure
    End Class

    Note the list is used for the order lines.  Note also how the ToString method of the structure is used to desplay each order line int eh list.  You must look up the TryParse method in the online help so you can see what this statement is doing and how it works.

    • Write the code you will use to input the data. Assume that you are getting
    the data from TextBox controls.

    That's very poor expression - you do not input the data.  You put code in the button click event (as above) to get the data that the user has already input.  'Input' as used here must mean "create an order line data structure, and populate it with the data input by the user".

    • Allow the user to enter up to 10 different items.

    Not done in this example.  You need to add code to check the size of the list to see if the user has exceeded the limit. Note that this part of the assignment might have been included because there was an assumption that you would use arrays (some of these exercises are very old).  As you are using a List instead of arrays then there is no need for such a restriction.

    • Write the code for determining the order total.

    The total for each line is done for the txtTotal textbox, and also in the ToString method of the structure. A useful extra-credit exercise is to create a method in the structure that returns the total for you, so you are not doing the calculation in two different places.

    To create the order total you need to iterate through your list of order lines, accumulating the line totals.  That could be done in the ListUpdate method.

    • Edited by Acamar Saturday, October 20, 2012 1:13 AM sp
    • Proposed as answer by Frank L. Smith Saturday, October 20, 2012 1:23 AM
    • Marked as answer by Mark Liu-lxf Tuesday, October 23, 2012 8:18 AM
    Saturday, October 20, 2012 1:03 AM
  • @Acamar -->

    Well done. :)


    Please call me Frank :)

    Saturday, October 20, 2012 1:23 AM
  • thank you everybody. I really appreciate the help.

    LC

    Saturday, October 20, 2012 6:33 PM
  • Testing Bold.

    Thanks!


    Ed Price (a.k.a User Ed), SQL Server Customer Program Manager (Blog, Twitter, Wiki)

    Wednesday, October 31, 2012 10:07 PM
  • Test Failed

    Thursday, November 1, 2012 4:17 AM
  • Test Failed


    Test failed? Looks bold.

    Ed Price (a.k.a User Ed), SQL Server Customer Program Manager (Blog, Twitter, Wiki)

    Saturday, November 3, 2012 10:38 AM
  • Ed 

    I had made 2 images for you in different browsers IE10 and Chrome, you have to believe us, there is no bold at all. 

    I've tried twice to send it by renewing the message complete and then doing it again, it fails consequently by unexpected errors.

    Thanks for doing this because it should be midnight Friday eve now at Redmond.

    For this one I had also to renew the thread again before I got through the unexpected errors.


    Success
    Cor

    Saturday, November 3, 2012 11:32 AM
  • Doesn't appear bold to me. Anywhere. All of the forums that have the "new" formatting do not show any bold or italics.

    The only time we see the formatting that was actually used, is when we're writing the post, or editing one. (I've bolded the word "actually", I see it in the editor.


    Yann - LightSwitch Central - Click here for FREE Themes, Controls, Types and Commands
     
    Please click "Mark as Answer" if a reply answers your question. Please click "Vote as Helpful" , if you find a reply helpful.
     
    By doing this you'll help others to find answers faster.

    Tuesday, November 6, 2012 10:14 AM
  • Now that it's posted, I don't see it any more.

    Yann - LightSwitch Central - Click here for FREE Themes, Controls, Types and Commands
     
    Please click "Mark as Answer" if a reply answers your question. Please click "Vote as Helpful" , if you find a reply helpful.
     
    By doing this you'll help others to find answers faster.

    Tuesday, November 6, 2012 10:15 AM
  • And I do see it. Every time. I think the bold even got bigger than it was two months ago. Perhaps the team was trying to fix it by making it more obvious?

    However, this seems to be a browser or system issue.

    Why is that I can see it?


    Ed Price (a.k.a User Ed), SQL Server Customer Program Manager (Blog, Twitter, Wiki)


    Tuesday, November 6, 2012 6:52 PM
  • In another post, where you asked for a link to a specific post, I even included an image, showing you exactly how I see my reply (which contains bold & italic).

    I'm using:


    Yann - LightSwitch Central - Click here for FREE Themes, Controls, Types and Commands
     
    Please click "Mark as Answer" if a reply answers your question. Please click "Vote as Helpful" , if you find a reply helpful.
     
    By doing this you'll help others to find answers faster.

    Wednesday, November 7, 2012 1:44 AM