-3

我有一个值为 0.00 的文本框,然后我在转换时出错...但是我做了一个 0.00 的示例,而不是来自文本框,它正在工作。我该如何解决这个问题?

    Dim _Total, _Deduct, _Charges As String
    Dim _sss, _tax, _pf, _ph, _loan, _others, _hdmf, _cola, _allowance As Decimal

此行如果文本框和注释此行有效.. 但我使用此行不工作..

    _sss = txtSSS.Text : _ph = txtPH.Text : _tax = txtInTax.Text : _pf = txtPF.Text
    _loan = txtLoan.Text : _hdmf = txtHDMF.Text : _others = txtOther.Text
    _cola = txtCola.ToString : _allowance = txtAllowance.ToString

这一行是我给定的示例值...相同的值但文本框不起作用..这是有效的

    'This code when I uncomment.. this work..
    '_sss = "0.00": _ph = "0.00" : _tax = "0.00" : _pf = "0.00"
    '_loan = "0.00" : _hdmf = "50.00" : _others = "0.00"
    '_cola = "0.00" : _allowance = "0.00"

    _Charges = CDec(_cola) + CDec(_allowance)
    _Deduct = CDec(_sss) + CDec(_tax) + CDec(_pf) + CDec(_ph) + CDec(_loan) + CDec(_hdmf) + CDec(_others)

    _Total = CDec(_Charges) - CDec(_Deduct)

    lblDeduct.Text = Format((_Deduct), "currency")
    lblTotal.Text = FormatCurrency((_Total), 2, TriState.True, TriState.False, TriState.True)
4

1 回答 1

1

使用Decimal.TryParse

<!-- language : lang-vb -->
If Not Decimal.TryParse(txtSSS.Text, _sss) Then
    ' do something if the value doesn't convert
End If

根据您的评论并使用您的代码,看看这是否适合您(我使用 0 作为默认值)。如果您还没有Option Strict打开,请帮自己一个忙,然后这样做。

从上面的Option Strict链接:

将隐式数据类型转换限制为仅扩大转换,禁止后期绑定,并禁止导致 Object 类型的隐式类型。

Private Sub CalculateCurrency()
    If Not Decimal.TryParse(txtSSS.Text, _sss) Then _sss = 0D
    If Not Decimal.TryParse(txtPH.Text, _ph) Then _ph = 0D
    If Not Decimal.TryParse(txtInTax.Text, _tax) Then _tax = 0D
    If Not Decimal.TryParse(txtPF.Text, _pf) Then _pf = 0D
    If Not Decimal.TryParse(txtLoan.Text, _loan) Then _loan = 0D
    If Not Decimal.TryParse(txtHDMF.Text, _hdmf) Then _hdmf = 0D
    If Not Decimal.TryParse(txtOther.Text, _others) Then _others = 0D
    If Not Decimal.TryParse(txtCola.Text, _cola) Then _cola = 0D
    If Not Decimal.TryParse(txtAllowance.Text, _allowance) Then _allowance = 0D

    _Charges = CStr(_cola + _allowance)

    _Deduct = CStr(_sss + _tax + _pf + _ph + _loan + _hdmf + _others)

    _Total = CStr(CDec(_Charges) - CDec(_Deduct))

    lblDeduct.Text = Format((_Deduct), "currency")
    lblTotal.Text = FormatCurrency((_Total), 2, TriState.True, TriState.False, TriState.True)
End Sub
于 2012-07-16T02:23:43.510 回答