none
Convert my input in textbox to Decimal and input to listview(Please help me!!!)

    Question

  • This is the codes:

     Dim PC As New Product_Class

            With PC

                .product_name = txt_productname.Text
                .product_description = txt_productdescription.Text
                .product_price = Convert.ToDecimal(txt_productprice.Text.ToString())
                .product_category = cbo_productcategory.Text
                .product_quantity = Convert.ToDecimal(txt_productquantity.Text.ToString())
                If txt_productname.Text = "" And txt_productdescription.Text = "" And Convert.ToDecimal(txt_productprice.Text) And cbo_productcategory.Text = "Category Selection" And Convert.ToDecimal(txt_productquantity.Text) Then
                    MsgBox("Please Input a Data")
                    txt_productname.Focus()
                Else
                    .saveNewCategory(PC)
                End If
                txt_productname.Text = ""
                txt_productdescription.Text = ""
                txt_productprice.Text = ""
                cbo_productcategory.Text = "Category Selection"
                txt_productquantity.Text = ""
                Product_Class.populateProduct(Me.listview_category)
            End With
        End Sub

    Public Class Product_Class
        Public product_name As String
        Public product_description As String
        Public product_price As Decimal
        Public product_category As String
        Public product_quantity As Decimal
        Public Function saveNewProduct(ByVal product_name) As Boolean

            Dim is_foundproduct As Boolean = False
            Dim pc As New Product_Class
            pc.product_name = FRMAdmin.txt_productname.Text
            pc.product_description = FRMAdmin.txt_productdescription.Text
            pc.product_price = Convert.ToDecimal(FRMAdmin.txt_productprice.Text)
            pc.product_category = FRMAdmin.cbo_productcategory.Text
            pc.product_quantity = Convert.ToDecimal(FRMAdmin.txt_productquantity.Text)
            GLOBAL_VARS.product_list.Add(pc)
            Product_Class.populateProduct(FRMAdmin.Listview_product)
            MsgBox("New Product Added", MsgBoxStyle.Information)

            Return (0)

        End Function

     Public Shared Sub populateProduct(ByVal lsvproduct As ListView)
            lsvproduct.Items.Clear()
            For Each pc As Product_Class In GLOBAL_VARS.product_list
                Dim pcl As Integer = lsvproduct.Items.Count
                With lsvproduct
                    .Items.Add(pc.product_name)
                    .Items(pcl).SubItems.Add(pc.product_description)
                    .Items(pcl).SubItems.Add(Convert.ToDecimal(pc.product_price))
                    .Items(pcl).SubItems.Add(pc.product_category)
                    .Items(pcl).SubItems.Add(Convert.ToDecimal(pc.product_quantity))
                End With
            Next
        End Sub

    It's seems when i save .. its doesn't look like this 100.00

    its goes just like this 100 when i add to listview.. please helpp!!!

    somebody help me,

    xiao

    Wednesday, March 15, 2017 1:03 AM

All replies

  • Do you mean in the lines Convert.Todecimal(...)?

    If so there are many ways. You could use a toString with a NumberFormat string or a cultureInfo etc.

    [Note that usually, you would have to convert the converted number to a string again for displaying in a msgbox, I left out Option strict here, to keep it simple]

            Dim txt_productprice As String = "100.00"
            Dim ci As New System.Globalization.CultureInfo("en-Us")
            MessageBox.Show(Convert.ToDecimal(txt_productprice, ci.NumberFormat))

    Regards,

      Thorsten

    Wednesday, March 15, 2017 1:19 AM
  • Visual Basic has a lot of convert functions. 

    Sometimes it are just short ways to use system methods like system convert, sometimes they are optimized. 

    I prefer them already alone because it is less typing. 

    The question if you should use the classic C style try subs I avoid. I think it is better to avoid wrong typing in the textbox, that is easy code to make but another question.

    All VB conversion functions

    https://msdn.microsoft.com/en-us/library/s2dy91zy.aspx

    Be aware that VB uses internal the Englis notation (except SA) of the decimal point. Outside it is the language setting of the user used. 

    Therefore 

    dim aDecimalNumber = Cdec("1,01") results in most natural languages internal as a decimal with the value 1.01 (English notation)


    Success
    Cor



    Wednesday, March 15, 2017 6:35 AM
  • Xi,

    Maybe I'm not understanding your question but hopefully something in the following might help:

    When you're dealing with text, you need to validate that the text can be converted (cast) to a numeric type - a decimal in this case. You can do that with the .Validating event.

    In the following I do that and I test that the value entered to ensure that it passes the test that I put in the class - in this one, the price can be zero, but it can't be negative.

    Code For Class

    Public Class Products Private _name As String Private _description As String Private _price As Decimal Private _category As String Private Sub New(ByVal name As String, _ ByVal description As String, _ ByVal price As Decimal, _ ByVal category As String) _name = name.Trim _description = description.Trim _price = price _category = category.Trim End Sub Public Shared Sub _ AddNewProduct(ByVal productList As List(Of Products), _ ByVal name As String, _ ByVal description As String, _ ByVal price As Decimal, _ ByVal category As String) Try ValidateListIsNotNull(productList) If String.IsNullOrWhiteSpace(name) Then Throw New ArgumentException("The name cannot be null or empty.") ElseIf String.IsNullOrWhiteSpace(description) Then Throw New ArgumentException("The description cannot be null or empty.") ElseIf String.IsNullOrWhiteSpace(category) Then Throw New ArgumentException("The category cannot be null or empty.") Else Dim msg As String = PriceIsInRange(price) If Not String.IsNullOrWhiteSpace(msg) Then Throw New ArgumentOutOfRangeException("Price", msg) Else ' In reality you'd want to check for duplicates at ' this point but I won't do that here... productList.Add(New Products(name, description, price, category)) End If End If Catch ex As Exception Throw End Try End Sub Public Shared Function _ GetListViewItems(ByVal productList As List(Of Products)) As ListViewItem() Dim retVal() As ListViewItem = Nothing Try ValidateListIsNotNull(productList) If productList.Count > 0 Then Dim tempList As New List(Of ListViewItem) For Each prod As Products In productList Dim lvi As New ListViewItem(prod.Name) With lvi.SubItems .Add(prod.Category) .Add(prod.Description) .Add(prod.Price_String) End With tempList.Add(lvi) Next If tempList.Count > 0 Then retVal = tempList.ToArray End If End If Catch ex As Exception Throw End Try Return retVal End Function Public Shared Function ValidatePriceText(ByVal text As String) As String Dim retVal As String = Nothing Dim value As Decimal If Decimal.TryParse(text, value) Then retVal = PriceIsInRange(value) Else retVal = "This is not a valid price." End If Return retVal End Function Private Shared Function PriceIsInRange(ByVal price As Decimal) As String If Not price >= 0 Then Return "The price must be a non-negative amount." Else Return Nothing End If End Function Private Shared Sub ValidateListIsNotNull(ByVal list As List(Of Products)) Try If list Is Nothing Then Throw New ArgumentNullException("List(Of Products)", "Cannot be null." & vbCrLf) End If Catch ex As Exception Throw End Try End Sub Public ReadOnly Property Category As String Get Return _category End Get End Property Public ReadOnly Property Description As String Get Return _description End Get End Property Public ReadOnly Property Name As String Get Return _name End Get End Property Public ReadOnly Property Price As Decimal Get Return _price End Get End Property Public ReadOnly Property Price_String As String Get Return _price.ToString("c2") End Get End Property End Class


    Code For Form1

    Option Strict On Option Explicit On Option Infer Off Public Class Form1 Private prodList As List(Of Products) Private ep As ErrorProvider Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles MyBase.Load prodList = New List(Of Products) btn_AddProduct.Enabled = False ep = New ErrorProvider With ListView1 .Columns.Add("Product Name", 100, HorizontalAlignment.Center) .Columns.Add("Category", 100, HorizontalAlignment.Center) .Columns.Add("Description", 175, HorizontalAlignment.Center) .Columns.Add("Price", 100, HorizontalAlignment.Center) .FullRowSelect = True .GridLines = True .MultiSelect = False .View = View.Details End With End Sub Private Sub _ MinimumRequired(sender As System.Object, _ e As System.EventArgs) _ Handles tb_Name.TextChanged, _ tb_Category.TextChanged, _ tb_Description.TextChanged, _ tb_Price.TextChanged ep.Clear() If VerifyInfo() Then btn_AddProduct.Enabled = True Else btn_AddProduct.Enabled = False End If End Sub Private Sub _ tb_Price_Validating(sender As Object, _ e As System.ComponentModel.CancelEventArgs) _ Handles tb_Price.Validating If tb_Price.Text.Trim <> "" Then Dim errorMessage As String = Products.ValidatePriceText(tb_Price.Text) If Not String.IsNullOrWhiteSpace(errorMessage) Then Dim sb As New System.Text.StringBuilder sb.AppendLine(errorMessage) sb.AppendLine() sb.AppendLine("Please re-enter the price or clear the") sb.AppendLine("text entirely in order to continue.") sb.Remove(sb.Length - 2, 2) ep.SetError(tb_Price, sb.ToString) e.Cancel = True btn_AddProduct.Enabled = False End If End If End Sub Private Sub _ btn_AddProduct_Click(sender As System.Object, _ e As System.EventArgs) _ Handles btn_AddProduct.Click Try With btn_AddProduct .Enabled = False .Refresh() End With Products.AddNewProduct(prodList, tb_Name.Text, tb_Description.Text, _ CDec(tb_Price.Text), tb_Category.Text) If prodList.Count > 0 Then Dim lvItems As ListViewItem() = Products.GetListViewItems(prodList) If lvItems IsNot Nothing Then With ListView1 .Items.Clear() For Each lvi As ListViewItem In lvItems .Items.Add(lvi) Next End With End If End If ClearText() Catch ex As Exception MessageBox.Show(String.Format("An error occurred:{0}{0}{1}", _ vbCrLf, ex.Message), _ "Exception Thrown", _ MessageBoxButtons.OK, _ MessageBoxIcon.Warning) End Try End Sub Private Sub ClearText() tb_Name.Clear() tb_Category.Clear() tb_Description.Clear() tb_Price.Clear() End Sub Private Function VerifyInfo() As Boolean Dim cnt As Integer = 0 If Not String.IsNullOrWhiteSpace(tb_Name.Text) Then cnt += 1 End If If Not String.IsNullOrWhiteSpace(tb_Category.Text) Then cnt += 1 End If If Not String.IsNullOrWhiteSpace(tb_Description.Text) Then cnt += 1 End If If Not String.IsNullOrWhiteSpace(tb_Price.Text) Then cnt += 1 End If Return cnt = 4 End Function End Class


    The form that I set up is pretty basic:

    In the following I'll test the logic of validating the textbox for the price:

    I hope that helps. :)


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Wednesday, March 15, 2017 2:05 PM
  • i have also a question.. how i will get the total amount of listview into textbox if i get the sum of a specific column in listview.. :( its confusing ... i appreciate the answer.. its working perfectly thank you mr. Frank L. Smith
    Thursday, March 23, 2017 8:20 AM
  • why i cant insert images.. so that i can explain properly what i'm talking about 

    ;(

    Thursday, March 23, 2017 8:23 AM
  • why i cant insert images.. so that i can explain properly what i'm talking about 

    ;(

    You can use this button


    Success
    Cor

    Thursday, March 23, 2017 9:32 AM
  • i have also a question.. how i will get the total amount of listview into textbox if i get the sum of a specific column in listview.. :( its confusing ... i appreciate the answer.. its working perfectly thank you mr. Frank L. Smith

    Hi,

    In my opinion, "quantity" doesn't belong in that same class. It's up to you of course.

    You will have to make some decisions though: What happens if someone enters the same product twice? Will it increase the quantity and update that entry or should it be considered an error?

    Whichever way you choose, set the class up to handle that, including the math.

    Also, have you considered using a DataGridView instead of a ListView? It's a much better control for this.


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Thursday, March 23, 2017 12:05 PM
  • i dont know datagridview thats the problem.. i only know listview :( so sorry. i cant explain very well.. if i dont have any images... images its has an error . :( if a certain product get out it will deduct the quantity if the product you want to add .. for example 100 the quantity if product out 10 then its total 90 then if i add +10 again it goes 100 again.. i hope you understand what i mean.. :( thank you so much for understand my problem..
    Friday, March 24, 2017 10:28 AM
  • i dont know datagridview thats the problem.. i only know listview :( so sorry. i cant explain very well.. if i dont have any images... images its has an error . :( if a certain product get out it will deduct the quantity if the product you want to add .. for example 100 the quantity if product out 10 then its total 90 then if i add +10 again it goes 100 again.. i hope you understand what i mean.. :( thank you so much for understand my problem..

    When I get back in I'll try to come up with an example that I can show.

    With any luck I'll have something back here in a few hours or so.


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Friday, March 24, 2017 11:50 AM
  • Thank you so much sir for helping my problem..
    Friday, March 24, 2017 9:59 PM
  • Thank you so much sir for helping my problem..

    Bear with me until this weekend please.

    I'll have something then. :)


    "A problem well stated is a problem half solved.” - Charles F. Kettering


    Friday, March 24, 2017 10:44 PM
  • ok sir.. i will wait .. i hope you understand my problem.. thank you!
    Saturday, March 25, 2017 12:05 AM
  • ok sir.. i will wait .. i hope you understand my problem.. thank you!

    I'll get on it this weekend - "real work" gets in the way sometimes. ;-)

    *****

    This is really something more suited for a database solution but that's not to say that we can't do this using just classes.

    I was thinking today that I want to show you what I mean about the separation of what's what, and I have some ideas -- I just couldn't get back to this, but I will over the weekend.


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Saturday, March 25, 2017 12:19 AM
  • its just a collection through global_vars . i hope you can understand.. it doens't use any database..
    Saturday, March 25, 2017 2:06 PM
  • its just a collection through global_vars . i hope you can understand.. it doens't use any database..

    Right, I understand.

    What I meant though is that this would be better suited with a real RDBMS, but I'm working on it now with just classes.


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Saturday, March 25, 2017 2:28 PM
  • Thank you sir.
    Saturday, March 25, 2017 3:37 PM
  • Xiaochiin,

    In thinking about how best to do this, I decided to put it all together and give you the project folder with everything in it. Trying to explain what to set up and all that would be difficult at best.

    I have the project directory zipped up and uploaded here.

    The zip file has just one entry (the directory) so once you download that zip file, extract it somewhere on your computer and open it with Visual Studio. Because I use an older version than you do, VS will prompt you to convert it. Just follow the prompts and it should all work.

    As you can tell by the name of the zip file, what I’ve done here is to set something up wherein the “products” are groceries and it’s based on some data that I put together a few years ago. You might want to have a look at the XML file on my site here (be patient and let it load).

    The other day I said that I don’t think the quantity belongs in the same class as your products, and this is based on that: The products – groceries in this example – aren’t part of an order or inventory or any of that; the products are the products.

    This is where a good database is a better animal for managing something like this but for this example project, there is no database at all.

    *****

    First things first here: When you get it converted and opened in Visual Studio, please take a look at Solution Explorer:

    There are two projects in the solution as you see there. I put the “Products” together yesterday afternoon/earlier this morning. It runs on a background thread, gets the data from the online XML file, and loads all of that into a collection class that’s in that assembly.

    Don’t worry so much about how that’s done. It’s all in there if you want to look but it’s not anything that you need to change, so just let it do what it does. ;-)

    When you run it, you’ll see it showing that it’s getting the data:

     

    Note: The prices shown are total nonsense! During the loading of the data from my website, the code of the assembly is generating a random decimal value to use for the price, so don’t infer anything about the prices at all.

     

    It shouldn’t take but a few seconds to load it all. Once it completes, it’s put all of the grocery information into a class-scoped instance called “_groceries”:

    Private WithEvents _groceries As Groceries

    Using a breakpoint, you can see that it’s loaded a fair amount of data in those short few seconds:

    Almost 8900 grocery items – so we have a lot to work with. ;-)

    You don’t need to set a breakpoint at first (just run it and experiment with it as a user), but eventually I think you’ll find it beneficial if you do step through the various parts of the code.

    The “base” data – the groceries – are never changed. One of the reasons that I set my assembly up the way that I did is so that you can’t edit it; it’s strictly read-only and that goes back to what I said about the quantity being separate from your data.

    *****

    I’ll explain what you’ll see when you run it:

    Once it loads the data from my site (about three seconds here), the menu bar will be enabled:

    There’s nothing showing right now because you haven’t yet told it what to show. Clicking the menu bar item will show another form modally allowing you to select a product based on the category:

    When you select a category from the combo…

    It will then get 15items and show them to you in a ListView:

    ** Note: The 15 items are the default but you can change that. In Form1’s code on line 47, you’ll see this:

    Using ggd As New GetGroceriesData(_groceries)

    Change that some by adding a value for the optional parameter. For example, if you wanted to see 50 items instead of the default 15, use this:

    Using ggd As New GetGroceriesData(_groceries, 50)

    If you want no restriction on the quantity it gets, use this:

    Using ggd As New GetGroceriesData(_groceries, Nothing)

    That might be in the thousands though, so do know that! ;-)

    Back to the using the program, select a row and click the “OK” button:

    When you select a grocery item, it assumes a quantity of 1 but as I’ll show you shortly, you can alter the quantity to anything you want (but do note that negative quantities will be set to zero instead of a negative value).

    I’ll add some more grocery items and as I do, the totals are automatically updated:

    There are two ways that you can change the quantity (and thus the extended price and total price of the order). The first way is to select the grocery item you want to change and click the button at the bottom to change the price:

    As shown above, there’s another form shown modally where you can change the quantity.

    When it returns, everything is updated. The second way to change the quantity is to add it again:

    As before, it assumes a quantity of one:

    *****

    There’s a class named “ProductOrder” in the code that’s doing all of this. The class named “Groceries” is just the data for the products, not the order, so have a look at all of that and I hope you find it useful. :)


    "A problem well stated is a problem half solved.” - Charles F. Kettering


    • Edited by Frank L. Smith Saturday, March 25, 2017 7:23 PM ...link bad
    Saturday, March 25, 2017 7:21 PM
  • Thank you so much for the information give sir charles..its very help.. i will tell you if it works with my current project.. im blessed to have you sir..
    Saturday, March 25, 2017 11:53 PM
  • Thank you so much for the information give sir charles..its very help.. i will tell you if it works with my current project.. im blessed to have you sir..

    Uhh, were you addressing me?

    I'm Frank, not Charles. ;-)

    If it was to me then run it and test it and eventually, put a breakpoint in so you can see what I'm doing there.

    I hope it helps. :)


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Sunday, March 26, 2017 12:15 AM
  • so sorry sir frank.. i though "A problem well stated is a problem half solved.” - Charles F. Kettering hehehehe.. ok sir i will test right now 

    Sunday, March 26, 2017 12:43 AM
  • i see the program already.. i was confuse .. how can i able to determine if the quantity of the product is 0 already?? then how i can add quantity of a certain product ? :(
    Sunday, March 26, 2017 1:47 AM
  • i see the program already.. i was confuse .. how can i able to determine if the quantity of the product is 0 already?? then how i can add quantity of a certain product ? :(

    Look at the code on Form1. At the end of the class (Form1), starts another class:

    Public Class ProductOrder

    It has a nested class named "OrderItem". Each entry (that is, each line item) is an instance of that nested class:

    Put a breakpoint on line 512 and run the program. When you add a product entry, you'll see what it does to update the quantity.


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Sunday, March 26, 2017 9:18 AM
  • do you have any email add.. i will give you the project so that you can see what i mean..

    I don't give out my e-mail address here but it wouldn't do any good anyway. The fact that I use an older version, I can't open yours anyway.

    I'd suggest that you remove yours in the message above - the spam you'll get otherwise will be horrendous!

    I hate that after all this we're still not connecting and I wasn't able to get the problem solved for you.

    Sorry about that.


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Sunday, March 26, 2017 4:08 PM
  • its not like that sir.. your helping me big.. i just want you to see my project if its correct or wrong.. so that i can determine which was my wrong program.. pls sir...
    Sunday, March 26, 2017 11:31 PM
  • its not like that sir.. your helping me big.. i just want you to see my project if its correct or wrong.. so that i can determine which was my wrong program.. pls sir...

    I didn't mean that I won't help - I will if I can, I just won't be able to open the project folder is all.

    I don't know if you're aware or not, but the VB files (*.vb) are really just text files, so I can still see the code as text. I might not be able to do anything but look, but that's better than nothing.

    *****

    I'm shutting down for the night but how about do this: Explain what your program is all about and what you want to do? What are the products, for example?

    I'm not a database guy but it really does seem to need one. Have you considered that?

    I'll look back in tomorrow.


    "A problem well stated is a problem half solved.” - Charles F. Kettering


    • Edited by Frank L. Smith Sunday, March 26, 2017 11:42 PM re-worded...
    Sunday, March 26, 2017 11:41 PM
  • i have a problem with this.. i cant post any imgs.. itry to click insert image.. its always goes error :( thats why.. i cant explain..
    Monday, March 27, 2017 1:21 AM
  • body text cannot contain images or links until we are able to verify your account?? this is the promp error..
    Monday, March 27, 2017 1:23 AM
  • body text cannot contain images or links until we are able to verify your account
    See:
    https://social.msdn.microsoft.com/Forums/en-US/054fddac-7164-4412-a077-f57ba5dd9e5d/verify-your-account-38?forum=reportabug
    Monday, March 27, 2017 2:07 AM