Reputation: 13
Private Sub btnOne_Click(sender As Object, e As EventArgs) Handles btnOne.Click
txtAnswer.AppendText(1)
End Sub
So this is my code (It's for 0 through to 9 and a dot for decimal points).
I'm working on calculator for an assignment, my question is, can I make this more efficient so I don't have a lot code doing the same thing?
I had considered setting up a function to read the contents of the buttons and add them to the textbox, but then the operation buttons and clear buttons would just add to the textbox instead of performing the code assigned to them.
Upvotes: 1
Views: 50
Reputation: 7880
You could create a function just like that, but it should read the number from the sender's Text
property, and only assign the number buttons to that function in the OnClick
event.
The other buttons will have their own OnClick
methods, and you should make a generic function like in this case when you find a common behavior in some of them. Perhaps you could do another generic function for all +
-
/
x
operators, it that's appropriate.
Upvotes: 0
Reputation: 8033
you can create one method for the numeric buttons and add their value to the Tag Object. Then you can just reference the tag object to append to the text
Private Sub NumericButtons_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim btn As Button
btn = sender
txtAnswer.AppendText(btn.Tag)
End Sub
Upvotes: 1