Reputation: 35
I'm new to programming and I have a problem. I have two buttons and a textbox. When I press the button, a number will show on the textbox, but when I press the second button the number in the textbox overwrites it and replaces it instead of adding to it in the textbox. How do I fix this? I want the values to add instead of replacing it.
public partial class Form1 : Form
{
int value1 = 0;
int value2 = 0;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
value1++;
textBox1.Text = value1.ToString();
}
private void button2_Click(object sender, EventArgs e)
{
value2 += 2;
textBox1.Text = value2.ToString();
}
}
}
Upvotes: 1
Views: 4473
Reputation: 186668
If you want to add two integers and assign the result back to textBox1
you have to
textBox1.Text
to integer: int.Parse(textBox1.Text)
int.Parse(textBox1.Text) + value2
string
: (...).ToString()
Implementation:
private void button2_Click(object sender, EventArgs e) {
value2 += 2;
textBox1.Text = (int.Parse(textBox1.Text) + value2).ToString();
}
Edit: If there's a possibility that textBox1.Text
doesn't contain a valid integer value (say, textBox1.Text
is empty) you can use int.TryParse
:
private void button2_Click(object sender, EventArgs e) {
if (int.TryParse(textBox1.Text, out var v)) {
value2 += 2;
textBox1.Text = (v + value2).ToString();
}
else {
//TODO: textBox1.Text is not a valid integer; put relevant code here
}
}
Upvotes: 4
Reputation: 347
Add this line:
textBox1.Text = (int.parseInt(textBox1.Text) + value2).toString();
after
value2 += 2;
into your button2_click method:
Upvotes: 0
Reputation: 956
You're using two separate variables (value1
and value2
above) to store the results of each button click, depending in which button was clicked. Think of it like this:
On program start:
value1 = 0
value2 = 0
User clicks button 1, which executes button1_Click. This increments value1 (via value1++
), so the two variables look like this:
value1 = 1
value2 = 0
User then clicks button 2, which executes button2_Click. This sets value2 to whatever was previously in value2 + 2. However, note that the value of value1 is unchanged:
value1 = 1
value2 = 2
By having separate variables, each button click is operating on a different value. I would modify your code so there is only one value
variable that both _Click functions modify.
Upvotes: 0