locked
listview column currency format RRS feed

  • Question

  • I have 2 columns and the second column is currency. I cant seem to format it to currency. Please help
    Wednesday, January 25, 2017 1:21 AM

Answers

  • I have 2 columns and the second column is currency. I cant seem to format it to currency. Please help

    You might also consider using a DataGridView along with a DataTable as the DataSource - it's a better control for showing tabulated data (in my opinion).

    "One who has no vices also has no virtues..."

    • Marked as answer by bobo040 Wednesday, January 25, 2017 11:12 AM
    Wednesday, January 25, 2017 1:39 AM
  •  A ListViewItem and its sub items Text property takes a String.  So,  if you are assigning a Double or Decimal type value to the Text property,  you can use the ToString() method and use the "C" format from the Standard Numeric Format Strings for currency.  For example...

            Dim SomeValue As Double = 10.5355
            Dim lvi As ListViewItem = ListView1.Items.Add("Some Text In Column 1")
            lvi.SubItems.Add(SomeValue.ToString("C2")) 'add the currency to column 2
    


    If you say it can`t be done then i`ll try it

    • Proposed as answer by Frank L. Smith Wednesday, January 25, 2017 1:37 AM
    • Marked as answer by bobo040 Wednesday, January 25, 2017 11:12 AM
    Wednesday, January 25, 2017 1:34 AM

All replies

  •  A ListViewItem and its sub items Text property takes a String.  So,  if you are assigning a Double or Decimal type value to the Text property,  you can use the ToString() method and use the "C" format from the Standard Numeric Format Strings for currency.  For example...

            Dim SomeValue As Double = 10.5355
            Dim lvi As ListViewItem = ListView1.Items.Add("Some Text In Column 1")
            lvi.SubItems.Add(SomeValue.ToString("C2")) 'add the currency to column 2
    


    If you say it can`t be done then i`ll try it

    • Proposed as answer by Frank L. Smith Wednesday, January 25, 2017 1:37 AM
    • Marked as answer by bobo040 Wednesday, January 25, 2017 11:12 AM
    Wednesday, January 25, 2017 1:34 AM
  • I have 2 columns and the second column is currency. I cant seem to format it to currency. Please help

    You might also consider using a DataGridView along with a DataTable as the DataSource - it's a better control for showing tabulated data (in my opinion).

    "One who has no vices also has no virtues..."

    • Marked as answer by bobo040 Wednesday, January 25, 2017 11:12 AM
    Wednesday, January 25, 2017 1:39 AM
  • Thanks I will try
    Wednesday, January 25, 2017 2:58 AM
  • Hi bobo040,

    Thank you for posting here.

    Use the FormatCurrency function to return an expression formatted as a currency value. And you could also use format string to suit. Like this:

    ListView1.View = View.Details
            ListView1.Columns.Add("Column1")
            ListView1.Columns.Add("Column2")
            ListView1.Items.Add(New ListViewItem(New String() {"1", FormatCurrency(100000, , , TriState.True, TriState.True)}))
            ListView1.Items.Add(New ListViewItem(New String() {"2", Format(25500000, "#,##0.00")}))

    Best Regards,

    Neda Zhang


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, January 25, 2017 6:00 AM
  • Thanks I will try

     Let us know how you make out with it.  If you have a problem,  then post your code that is relative to formatting the value and adding it to the listview so we can help further.  8)


    If you say it can`t be done then i`ll try it

    Wednesday, January 25, 2017 10:07 AM
  • Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            Dim item As New ListViewItem(TextBox2.Text)
            Dim TotalSum As Double = 0
            Dim TempDbl As Double
            For Each item In ListView1.Items
                If Double.TryParse(item.SubItems.Item(1).Text, TempDbl) Then
                    TotalSum += TempDbl
                End If
            Next
            Dim item1 As New ListViewItem("Total Amount:", 0)
            item1.SubItems.Add(TotalSum)
            'then we add this item to the ListView  
            ListView1.Items.Add(item1)
        End Sub

    The above code gives me a total in column 2 of my listview. The cost is added by a textbox individually on another button. I can format the textbox to show currency but when I do that the total ends up as 0. I need it to total as currency.
    Wednesday, January 25, 2017 11:33 AM
  • I need it to total as currency.

    For currency you should use Decimal because of precision but that aside, don't mix up the types and what you're trying to do.

    In your case, you're dealing with strings. Deal with the actual numeric type then display it as a formatted string.

    *****

    I said last night that a DGV (with a data source behind it) is a better animal and I'll show you what I mean - and reinforce the part about types - in the following. If you feel like it, you can repeat it.

    In the form, I put two panels; one docked to the top and the other docked to the bottom. In the top panel I put a BindingNavigator and a DataGridView and in the bottom panel I put a ListView:

    This way I can make a direct comparison which follows.

    I start with a simple class and a collection (a list in this case) of instances. The following looks a bit complex but it's not really:

    Option Strict On Option Explicit On Option Infer Off Public Class Form1 Private Class PotatoRetailPrice Public Property BagSize As Integer Public Property RetailPrice As Decimal End Class Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles MyBase.Load With DataGridView1 .AllowUserToAddRows = False .AllowUserToDeleteRows = False .AllowUserToOrderColumns = False .AllowUserToResizeRows = False .AlternatingRowsDefaultCellStyle.BackColor = Color.Aquamarine .ReadOnly = True .SelectionMode = DataGridViewSelectionMode.FullRowSelect .MultiSelect = False .RowHeadersVisible = False .RowTemplate.Height = 25 .EnableHeadersVisualStyles = False With .ColumnHeadersDefaultCellStyle .Font = New Font("Tahoma", 9, FontStyle.Bold) .BackColor = Color.LightGreen .WrapMode = DataGridViewTriState.True .Alignment = DataGridViewContentAlignment.MiddleCenter End With .ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing .ColumnHeadersHeight = 50 .DataSource = Nothing .Enabled = False End With Dim priceList As New List(Of PotatoRetailPrice) With priceList .Add(New PotatoRetailPrice _ With {.BagSize = 3, .RetailPrice = 1.6D}) .Add(New PotatoRetailPrice _ With {.BagSize = 5, .RetailPrice = 2.55D}) .Add(New PotatoRetailPrice _ With {.BagSize = 10, .RetailPrice = 5D}) End With PopulateDGV(priceList) PopulateListView(priceList) End Sub Private Sub PopulateDGV(ByVal list As List(Of PotatoRetailPrice)) With BindingNavigator1 .BindingSource = Nothing .Enabled = False End With With DataGridView1 .DataSource = Nothing .Enabled = False End With If list IsNot Nothing AndAlso list.Count > 0 Then Dim dt As New DataTable Dim column As New DataColumn With column .DataType = System.Type.GetType("System.Int32") .ColumnName = "Bag Size" dt.Columns.Add(column) End With column = New DataColumn With column .DataType = System.Type.GetType("System.Decimal") .ColumnName = "Price Per Bag" dt.Columns.Add(column) End With Dim row As DataRow For Each spud As PotatoRetailPrice In list row = dt.NewRow row("Bag Size") = spud.BagSize row("Price Per Bag") = spud.RetailPrice dt.Rows.Add(row) Next Dim bs As New BindingSource _ With {.DataSource = dt} With DataGridView1 .SuspendLayout() .DataSource = bs With .Columns(0) .Width = 200 With .DefaultCellStyle .Alignment = DataGridViewContentAlignment.MiddleCenter .Format = "0 Pound Bag" End With End With With .Columns(1) .AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill With .DefaultCellStyle .Alignment = DataGridViewContentAlignment.MiddleCenter .Format = "c2" End With End With .ResumeLayout() .Enabled = True End With With BindingNavigator1 .BindingSource = bs .Enabled = True End With End If End Sub Private Sub PopulateListView(ByVal list As List(Of PotatoRetailPrice)) If list IsNot Nothing AndAlso list.Count > 0 Then With ListView1 .Columns.Add("Bag Size", 200, HorizontalAlignment.Left) .Columns.Add("Price Per Bag", 125, HorizontalAlignment.Left) .FullRowSelect = True .GridLines = True .MultiSelect = False .View = View.Details End With For Each spud As PotatoRetailPrice In list Dim lvItem As New ListViewItem(spud.BagSize.ToString & " Pound Bag", 0) lvItem.SubItems.Add(spud.RetailPrice.ToString("c2")) ListView1.Items.AddRange(New ListViewItem() {lvItem}) Next End If End Sub End Class


    To start with, have a look at what's displayed when I run it:

    The DGV is certainly more visually appealing - and that's good of course - but because of what's behind it (a DataTable), it works better too. I can show what I mean by sorting the columns of the DataGridView:

    Please notice that the sort order is correct and it's most obvious with the names being sorted (the last two screenshots).

    The reason that it sorted the way you would expect it to is because the data itself is a numeric type, so that's what it's sorted on.

    With a ListView, everything is just a string; it doesn't know one string from another.

    I hope this helps it to make a little more sense?


    "One who has no vices also has no virtues..."

    Wednesday, January 25, 2017 1:28 PM
  • I have a combobox which you select an item, a textbox that you enter the cost in, and a button that drops both into a listview. That all works. On another button I have code that adds up everything and puts the total in column 2. That works. I added formatcurrency on the textbox and everything still works but the total shows up as 0. Here is the code I need to fix to except the total as currency. 

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            TextBox1.Text = ComboBox1.SelectedItem
            Dim item As New ListViewItem(TextBox1.Text)
            TextBox2.Text = FormatCurrency(TextBox2.Text)
            item.SubItems.Add(TextBox2.Text)
            ListView1.Items.Add(item)
            TextBox1.Clear()
            TextBox2.Clear()
        End Sub
        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            Dim item As New ListViewItem(TextBox2.Text)
            Dim TotalSum As Double = 0
            Dim TempDbl As Double
            For Each item In ListView1.Items
                If Double.TryParse(item.SubItems.Item(1).Text, TempDbl) Then
                    TotalSum += TempDbl
                End If
            Next
            Dim item1 As New ListViewItem("Total Amount:", 0)
            item1.SubItems.Add(TotalSum)
            'then we add this item to the ListView  
            ListView1.Items.Add(item1)
        End Sub

    Wednesday, January 25, 2017 2:46 PM
  • I have a combobox which you select an item, a textbox that you enter the cost in, and a button that drops both into a listview. That all works. On another button I have code that adds up everything and puts the total in column 2. That works. I added formatcurrency on the textbox and everything still works but the total shows up as 0. Here is the code I need to fix to except the total as currency. 

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            TextBox1.Text = ComboBox1.SelectedItem
            Dim item As New ListViewItem(TextBox1.Text)
            TextBox2.Text = FormatCurrency(TextBox2.Text)
            item.SubItems.Add(TextBox2.Text)
            ListView1.Items.Add(item)
            TextBox1.Clear()
            TextBox2.Clear()
        End Sub
        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            Dim item As New ListViewItem(TextBox2.Text)
            Dim TotalSum As Double = 0
            Dim TempDbl As Double
            For Each item In ListView1.Items
                If Double.TryParse(item.SubItems.Item(1).Text, TempDbl) Then
                    TotalSum += TempDbl
                End If
            Next
            Dim item1 As New ListViewItem("Total Amount:", 0)
            item1.SubItems.Add(TotalSum)
            'then we add this item to the ListView  
            ListView1.Items.Add(item1)
        End Sub

    I don't know who you're talking to, but the best way to figure out what's going on is to put a breakpoint in and step into each line. As you do, you can then inspect the value of all variables which are then in scope:

    https://blogs.msdn.microsoft.com/visualstudioalm/2016/07/15/7-ways-to-look-at-the-values-of-variables-while-debugging-in-visual-studio/

    You're in the best position to figure out what you have and what's not working correctly.


    "One who has no vices also has no virtues..."

    Wednesday, January 25, 2017 2:54 PM
  • Bob,

    Look carefully at this line:

    If Double.TryParse(item.SubItems.Item(1).Text, TempDbl) Then
        TotalSum += TempDbl
    End If

    Do be sure to put the breakpoint on the "If" and step through it.

    See if that helps you determine what's going on?

    https://msdn.microsoft.com/en-us/library/994c0zb1(v=vs.110).aspx

    I think you'll find that's where the problem is, but if you find it then you'll understand better just what's going on.

    ***** Try This To See Why *****

            Dim s As String = "This isn't a number"
    
            Dim tempDbl As Double
    
            If Double.TryParse(s, tempDbl) Then
                MessageBox.Show("Here")
            End If
    
            s = "$12.34"
    
            If Double.TryParse(s, tempDbl) Then
                MessageBox.Show("Here")
            End If
    
            Stop

    See now what's happening?


    "One who has no vices also has no virtues..."


    Wednesday, January 25, 2017 3:05 PM