简体   繁体   English

我如何将一个文本框的数量与另一个文本框相加 VB.NET

[英]How I Do Sum One Textbox Amount to another Text Box VB.NET

I have two text boxes TextBox1 and TextBox2 .我有两个文本框TextBox1TextBox2 I want to add the TextBox2 amount in TextBox1 .我想在TextBox1添加TextBox2数量。 I have use the below but the answer is not correct.我使用了以下但答案不正确。

Private Sub TextBox2_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox2.TextChanged
    TextBox1.Text = Val(TextBox2.Text) + Val(TextBox1.Text)
    TextBox2.Text = (FormatNumber(TextBox2.Text))
End Sub

Your problem is where you put your code.你的问题是你把代码放在哪里。 It runs every time the text changes.每次文本更改时它都会运行。

So, when you enter 2 in the TextBox2 it adds 2 to the 200 in TextBox1 .因此,当您在TextBox2输入 2 时,它会将 2 添加到TextBox1的 200。 Now TextBox1 is 202.现在TextBox1是 202。

You enter 0 in TextBox2 .您在TextBox2输入 0。 TextBox2 is now 20. The code runs and 20 +202 = 222, the new value in TextBox1 . TextBox2现在是 20。代码运行并且 20 +202 = 222, TextBox1的新值。

Finally you enter 0. The value in TextBox1 is 222 + 200 = 422 .最后输入 0。 TextBox1值为 222 + 200 = 422

You could see this happen if you set a break point in the code and stepped through line by line.如果您在代码中设置断点并逐行执行,您就会看到这种情况。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim TB1Integer As Integer
    Dim TB2Integer As Integer
    If Integer.TryParse(TextBox1.Text, TB1Integer) AndAlso Integer.TryParse(TextBox2.Text, TB2Integer) Then
        TextBox1.Text = CStr(TB1Integer + TB2Integer)
    Else
        MessageBox.Show("Please enter a number in both boxes.")
    End If
End Sub

I used Integer.TryParse to validate the TextBox entries.我使用Integer.TryParse来验证 TextBox 条目。 It is much more reliable than the old Val from VB6.它比 VB6 中的旧 Val 可靠得多。 .TryParse returns a Boolean so can be used in a an If statement. .TryParse返回一个布尔值,因此可以在 If 语句中使用。 It also fills the second parameter with the numeric value if successful.如果成功,它还用数值填充第二个参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM