Converting from lbl.Text to currecy

Hekzdaddy 121 Reputation points
2021-04-12T01:20:26.74+00:00

In the Case statement below, I am getting an error when trying to convert the results on lblTotal.Text to Currency. Any tips and suggestions would be helpful.

Case strCalculus
lblSubtotal.Text -= decCalculus
lblTax.Text -= decCalculus * decTAX_RATE
lblTotal.Text = lblSubtotal.Text + lblTax.Text + lblShipping.Text
lblShipping.Text -= dblShippingCharge
Case strHistoryScotland
lblSubtotal.Text -= decHistoryScotland
lblTax.Text -= decHistoryScotland * decTAX_RATE
lblTotal.Text = lblSubtotal.Text + lblTax.Text + lblShipping.Text

            lblShipping.Text -= dblShippingCharge

    End Select
    lblTotal.Text = CDbl(lblTotal.Text).ToString("c")
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,580 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Cheong00 3,471 Reputation points
    2021-04-12T01:31:35.24+00:00

    Most probably the following line caused the value of lblTotal.Text not a proper number.

    lblTotal.Text = lblSubtotal.Text + lblTax.Text + lblShipping.Text
    

    Try use the following instead:

    lblTotal.Text = CStr(CDbl(lblSubtotal.Text) + CDbl(lblTax.Text) + CDbl(lblShipping.Text))
    

  2. Karen Payne MVP 35,116 Reputation points
    2021-04-12T02:50:33.303+00:00

    This will work

    Dim value As Double = 0
    If Double.TryParse(lblTotal.Text, value) Then
        lblTotal.Text = $"{value.ToString("c")}"
    Else
        lblTotal.Text = "Invalid value"
    End If
    

    Or create a currency label

    Public Class CurrencyLabel
        Inherits Label
        Public ReadOnly Property AsCurrent() As String
            Get
                Dim value As Double = 0
                If Double.TryParse(Text, value) Then
                    Text = $"{value.ToString("c")}"
                End If
    
                Return Text
    
            End Get
        End Property
    End Class
    
    0 comments No comments