'Numbers replace themselves after pressing a button in Visual Basic
I am trying to make a calculator app in vb.net and I coded so it places a number in the textbox above but when I press another number the previous one disappears. I am attaching a screenshot of the app and code.
Code:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Label1.Visible = False
Label2.Visible = False
Label3.Visible = False
Label4.Visible = False
End Sub
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Label1.Visible = True
Label2.Visible = False
Label3.Visible = False
Label4.Visible = False
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Label1.Visible = False
Label2.Visible = True
Label3.Visible = False
Label4.Visible = False
End Sub
Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click
Label1.Visible = False
Label2.Visible = False
Label3.Visible = True
Label4.Visible = False
End Sub
Private Sub Button13_Click(sender As Object, e As EventArgs) Handles Button13.Click
Label1.Visible = False
Label2.Visible = False
Label3.Visible = False
Label4.Visible = True
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
TextBox1.Text = Val(1)
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
TextBox1.Text = Val(2)
End Sub
End Class
Solution 1:[1]
See comments. But the short answer is that in the code provided, TextBox1.Text is being replaced with a single numeric value depending on the keypad button clicked. On each click, the additional number actually needs to be appended to whatever is currently in the textbox. eg. for Button2_Click:
Dim btn as Button = CType(sender, Button)
TextBox1.Text = TextBox1.Text & btn.Text
Also, since this code will work for each of the numeric keypad buttons, a single handler (any suitable name) can be used:
Private Sub NumberPad_Click(sender As Object, e As EventArgs) Handles Button1.Click, Button2.Click, Button3.Click, etc.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

