Reputation: 39
I have two text boxes TextBox1
and TextBox2
. I want to add the TextBox2
amount in TextBox1
. 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
Upvotes: 0
Views: 2472
Reputation: 15081
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
. Now TextBox1
is 202.
You enter 0 in TextBox2
. TextBox2
is now 20. The code runs and 20 +202 = 222, the new value in TextBox1
.
Finally you enter 0. The value in TextBox1
is 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. It is much more reliable than the old Val from VB6. .TryParse
returns a Boolean so can be used in a an If statement. It also fills the second parameter with the numeric value if successful.
Upvotes: 3