2012-07-16 63 views
-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) 

回答

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 
+0

嗯..先生..什麼,如果文本框的值是動態的,可以通過改變textchange ..我真的DNT有一個好主意如何工作的.. TY的答覆.. – 2012-07-16 02:25:58

+0

@DeorwinBensurto把它放在TextBox的TextChanged事件 – 2012-07-16 02:27:21

+0

仍然不知道修復這個先生的好方法..我實際上使用貨幣價值計算..但仍然不能解決.. – 2012-07-16 02:51:49

相關問題