I believe the issue here is with state management. Web apps are stateless. You declare some fields at the top of your page class but fields are only useful for storing data while the page exists. Each request to the server (button click, for example) creates a new page. Hence you cannot store data in fields of a page across requests. The only way to store data in a web app across page requests is to use persistent storage like a database or, more likely, pass the data back to the client and have the client send it back on subsequent requests.
Note I would recommend you use descriptive control names rather than TextBox2
. It makes your code a lot easier to read and we don't have to guess. I'm assuming here that TextBox2
is a readonly control that displays the current value of your calculator.
When an operator is clicked you capture the current value of TextBox2
into both your first and second operand fields. That is wrong isn't it? Imagine I click the 4 button. Your number handler will store 4 into TextBox2
. Then I press the + operator button. You put 4 into both firstnum
and secondnum
. operator
gets the + and then you wipe TextBox2
. Now what? Your TextBox2
control which was tracking the current value is gone. You have 3 fields with values in them but the fields won't survive a page request so they are gone the next time a button is clicked.
The problem, I believe, is that you are assuming the fields will store their values across page requests and that isn't true. To work around this I would recommend you create hidden fields for any values you need to persist across requests that you don't want to show in the UI. I believe at a minimum this would be the current value of the calculator but would probably include the current operator, if any, as well. You could get away with not storing the current value provided TextBox2
always stored the current value but it looks like you use that for input as well. Therefore I would recommend that you create a separate, read only, textbox Results
that shows the current value and use TextBox2
only to show the current input as the user presses on number buttons. Each time they press an operator you take the current value of TextBox2
, use the operator to combine with Results
and then store the value back into Results
. You can then wipe TextBox2
for the next set of input. This will allow your data to persist across web requests.