[英]Adding numbers using button to a textbox
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();
}
}
} }
If you want to add two integers and assign the result back to textBox1
you have to 如果要添加两个整数并将结果分配回
textBox1
,则必须
textBox1.Text
to integer: int.Parse(textBox1.Text)
textBox1.Text
解析为integer: int.Parse(textBox1.Text)
int.Parse(textBox1.Text) + value2
int.Parse(textBox1.Text) + value2
string
: (...).ToString()
string
: (...).ToString()
Implementation: 执行:
private void button2_Click(object sender, EventArgs e) {
value2 += 2;
textBox1.Text = (int.Parse(textBox1.Text) + value2).ToString();
}
You're using two separate variables ( value1
and value2
above) to store the results of each button click, depending in which button was clicked. 您使用两个单独的变量(上面的
value1
和value2
)来存储每个按钮单击的结果,具体取决于单击了哪个按钮。 Think of it like this: 可以这样想:
On program start:
value1 = 0
value2 = 0
User clicks button 1, which executes button1_Click. 用户单击按钮1,执行button1_Click。 This increments value1 (via
value1++
), so the two variables look like this: 这会增加value1(通过
value1++
),因此这两个变量如下所示:
value1 = 1
value2 = 0
User then clicks button 2, which executes button2_Click. 然后用户单击按钮2,执行button2_Click。 This sets value2 to whatever was previously in value2 + 2. However, note that the value of value1 is unchanged:
这将value2设置为之前在value2 + 2中的值。但是,请注意value1的值不变:
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. 我会修改你的代码,因此只有一个
value
变量,两个_Click函数都会修改。
Add this line: 添加此行:
textBox1.Text = (int.parseInt(textBox1.Text) + value2).toString();
textBox1.Text =(int.parseInt(textBox1.Text)+ value2).toString();
after 后
value2 += 2;
value2 + = 2;
into your button2_click method: 进入你的button2_click方法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.