我正在编写一个 c# 窗口表单代码



我正在编写一个 c# 窗口表单代码 从 button1 和 button2 中获取数字,并将它们相加在一个文本框中,但编译器在 convert.toint32(textbox3.text( 语句上争论 而且它增加了two variable的值,three variable如何保持它不变但增加文本框的值 我需要解决方案吗?

int Three = 0;
int Two   = 0;
//int one   = 0;
int sum   = 0;
// int sum   = 0;
//int dec   = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// MessageBox.Show("Enter the teams` name");
}
private void button1_Click(object sender, EventArgs e)
{
//Three += 3;
//textBox3.Text = sum.ToString();
Three += 3;
sum = Convert.ToInt32(textBox3.Text) + Three;
textBox3.Text = sum.ToString();

}
private void button2_Click(object sender, EventArgs e)
{
Two += 2;
sum = Two + Convert.ToInt32(textBox3.Text) + Three;
textBox3.Text =Convert.ToInt32(textBox3.Text) + Two.ToString();


}
private void textBox3_TextChanged(object sender, EventArgs e)
{
textBox3.Text = 0.ToString();
} 

'

更改

sum = Convert.ToInt32(textBox3.Text) + Three;

sum = Convert.ToInt32(textBox3.Text == "" ? "0" : textBox3.Text) + 3;

另外,删除

private void textBox3_TextChanged(object sender, EventArgs e)
{
textBox3.Text = 0.ToString(); // this
}

因为它没有任何意义。

你的变量属于类,可以在构造函数中初始化它们。这可以通过多种方式完成,但您需要检查文本框是否有值,然后尝试转换并添加它。

private int Two;
private int Three;
private int sum;
public Form1()
{
this.Two = 0;
this.Three = 0;
this.sum = 0;
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// MessageBox.Show("Enter the teams` name");
}
private void button1_Click(object sender, EventArgs e)
{
this.Three += 3;
sum = textBox3.Text != String.Empty ? Convert.ToInt32(textBox3.Text) : 0;
textBox3.Text = Convert.ToString(sum + this.Three);
}
... same for number Two
private void textBox3_TextChanged(object sender, EventArgs e)
{
textBox3.Text = "0";
} 

最新更新