[英]button push increment number to a text box c# winform
This is for a project I'm doing for class, I'm trying to create a win form that will have 2 buttons one that will increment in the text box when the button is pushed and one that will decrement when a different button is pushed. 这是我正在上课的一个项目,我正在尝试创建一个将有2个按钮的赢奖形式,一个按钮在按下按钮时将在文本框中递增,而另一个按钮在按下另一个按钮时将递减。 。 I'm having trouble finding the right line that will do what I want. 我在寻找可以做我想做的正确路线时遇到了麻烦。 Is there someone that could help me out? 有没有人可以帮助我?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Project10TC
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
{
this.Close();
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Teancum Project 10");
}
private void button1_Click(object sender, EventArgs e)
{
int i = 1;
textBox1.Text = Convert.ToString(i++);
}
private void button2_Click(object sender, EventArgs e)
{
int i = 1;
textBox1.Text = Convert.ToString(i--);
}
private void button3_Click(object sender, EventArgs e)
{
textBox1.Clear();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
Since its a class project, I can only give you a hint. 由于它是一个课堂项目,因此我只能给您一个提示。
You need to define the variable i
outside of your button click events. 您需要在按钮单击事件之外定义变量i
。 Use the same variable in both events. 在两个事件中使用相同的变量。
Also look at the difference between i++
and ++i
还要看一下i++
和++i
之间的区别
Declare the i
variable as a field. 将i
变量声明为字段。 Besides I would use ++i
instead of i++
. 此外,我将使用++i
而不是i++
。 Otherwise you have different values in the textbox and in the variable. 否则,您在文本框中和变量中将具有不同的值。 Also, no need to use Convert.ToString()
. 另外,无需使用Convert.ToString()
。
public partial class Form1 : Form
{
int i;
public Form1()
{
InitializeComponent();
i = 0;
}
//...
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = (++i).ToString();
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = (--i).ToString;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.