Reputation: 187
adding value together.
so:
1 + 0 = 1
3 + 1 = 4
4 + 4 = 8
How do I get this, so that it starts off at 0, and i type in 1 into a txtbox, so it adds 1 to the total, next i type in 3, so it adds 3 to the total, which eqauls 4, now i type 4, and it adds 4 to the total, which means its at 8 now.
How do i write the code to keep adding to its self?
Upvotes: 0
Views: 2352
Reputation: 113442
int _total = 0;
public Form1()
{
InitializeComponent();
textBox1.KeyPress += textBox1_KeyPress;
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
int currentVal;
if(!int.TryParse(textBox1.Text, out currentVal))
return;
_total += currentVal;
textBox1.Clear();
MessageBox.Show(_total.ToString());
}
}
Upvotes: 1
Reputation: 38600
A text-box is two things: it's an interactive control on the screen into which a user can type and it's a piece of state: the text that they have entered.
As you want to be able to add what the user has typed in to the previous value, you will need to store the previous value, so you will need a variable in which to keep the running total. (A variable declared as a member of a class is called a field.)
You will also need to decide how you will know when the update the value in the text box. Should this be when the user hits Return or will you have a separate GUI button that they have to press? Either way, you will then need to add the current value of the text-box to the value in your field and then update the text in the text-box with the calculated sum. Don't forget to update the field with the new sum.
Upvotes: 1
Reputation: 158349
That sounds like homework, so I'll put the answer on a level so I don't give you the answer, but rather point out a direction.
The core problem is that you will need to store the value, so that it is available when you want to add the next number to it. If you declare a local variable inside a method, it gets initialized each time the method runs. So instead you will need to hold the value somewhere outside of the method, such as in a class field. Then you can simply add the value from the text box to the field by
int
)Upvotes: 10