2014-02-17 48 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'的原因是因为你永远不知道这个程序是如何在长期使用的。如果这是出于商业目的,有人可能会注意到这些值是四舍五入的(上或下)以及他们会去哪里?你,开发人员(或产品支持团队)。所以,最好只写一些额外的字符而不再回来。这是我的看法。 –

相关问题