添加两个文本框中的值,并在第三个文本框中显示总和

我已尝试将此代码从textbox1.text和textbox2.text添加到textbox3.text中

private void textBox1_TextChanged(object sender, EventArgs e) { if(!string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text)) { textBox3.Text = (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text).ToString()); } } private void textBox2_TextChanged(object sender, EventArgs e) { if(!string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text)) { textBox3.Text = (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text).ToString()); } } 

请帮助……有没有什么比将文本框的’格式’属性更改为一般数字?

你弄错了|| 应该替换为&&所以它将检查文本框是否填充了值。

您错误地使用了.ToString()方法,该方法仅适用于textbox2 ,请正确检查括号。

 textBox3.Text = (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text).ToString()); 

应该

 textBox3.Text = (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text)).ToString()); 

试试这个经过测试的代码。

  private void textBox1_TextChanged(object sender, EventArgs e) { if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text)) textBox3.Text = (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text)).ToString(); } private void textBox2_TextChanged(object sender, EventArgs e) { if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text)) textBox3.Text = (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text)).ToString(); } 

您当前的表达式在您的条件的第二部分中缺少否定(!)

此外,它应该是&& not ||

至于你的错误, 字符串的格式不正确 ,只要输入字符串无法转换为int ,你就会得到任何不安全的代码。 用try catch环绕它或使用Int32.TryParse

 private void **textBox_TextChanged**(object sender, EventArgs e) { int first = 0; int second= 0; if(Int32.TryParse(textBox2.Text, out second) && Int32.TryParse(textBox1.Text, out first)) textBox3.Text = (first + second ).ToString(); } } 

顺便说一句,就像Glenn所指出的那样,你只能使用一个事件处理程序,就像这个例子一样。

你可以这样做:

 if(!string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text)) { textBox3.Text =convert.toString(Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text)).toString(); } 

用这个。

  private void textBox2_TextChanged(object sender, EventArgs e) { if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text)) { textBox3.Text = Convert.ToString((Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text))); } } private void textBox1_TextChanged(object sender, EventArgs e) { if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text)) { textBox3.Text = Convert.ToString((Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text))); } }