2014-02-17 50 views
0

我有兩個文本框,一個可輸入值的位置,「£」字符位於文本框內,第二個文本框中的位置與「 「字符從MySQL表中需要被添加到第一個值。如何在兩個文本框中添加字符串值

發生什麼事情是,當我在第一個文本框中輸入值時,它不會被添加到第二個文本框中,它們都保持不變。看不出有什麼錯我的代碼:

Private Sub txtsurcharges_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtsurcharges.TextChanged 
    Dim c As Integer 
    c = Val(txtsurcharges.Text) + Val(txttotal.Text) 
    txttotal.Text = c 
End Sub 
+0

不使用'Val'它的工作原理與QBx-VB6中的一樣。如果您正在顯示貨幣,則保存爲整數將會丟失小數部分,請使用十進制或雙精度變量。由於這些似乎是用戶輸入,因此請使用'Decimal.TryParse'來獲取值。 – Plutonix

回答

1

嘗試這樣:

Private Sub txtsurcharges_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtsurcharges.TextChanged 
    Dim c As Double 'It is bad to use integers for currency, as integers cut off decimals.' 
    Dim surcharges As Double 
    Dim total As Double 'We also need to remove the £ char.' 
    If Double.TryParse(txtsurcharges.Text.Replace("£", ""), surcharges) = False Then 
     'It looks like it isnt possible to parse the string, probably because there is some special character or letter.' 
     'Some type of error handling will go here. (MsgBox or something else)' 
    End If 
    If Double.TryParse(txttotal.Text.Replace("£", ""), total) = False Then 
     'It looks like it isnt possible to parse the string, probably because there is some special character or letter.' 
     'Some type of error handling will go here. (MsgBox or something else)' 
    End If 
    c = surcharges + total 
    txttotal.Text = "£" & CStr(c) 
End Sub 

希望這有助於。

+0

這工作,謝謝 – Livaren

+0

沒問題。 :-) 另外,請注意,使用'「£」&somevar'更清潔,然後'String.Format(「£{0}」,somevar)' –

1

另外請確保您的txtsurcharges上有AutoPostBack = true或您的代碼不會觸發。

見你之前問:我的答案.... Adding the values of 2 textboxes to display result in one of them

MDTech.us_MAN也使得使用整數增加貨幣和我一樣的相同點。但是,你可能只有整個英鎊處理 - 你沒有指定。

最後,我會添加一個過濾器,將輸入限制爲txtsurcharges僅限數字。

+0

我使用上面的代碼,它的工作,但謝謝你的無論如何 – Livaren

+0

沒關係......在這種情況下,您必須擁有十進制貨幣值,上面的代碼纔可以。 – Mych

+0

@Mych:我建議使用'double'的原因是因爲你永遠不知道這個程序是如何在長期使用的。如果這是出於商業目的,有人可能會注意到這些值是四捨五入的(上或下)以及他們會去哪裏?你,開發人員(或產品支持團隊)。所以,最好只寫一些額外的字符而不再回來。這是我的看法。 –

相關問題