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

时间:2012-02-22 12:38:56

标签: c# winforms textbox

我已尝试将此代码从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());
        }
    }

请帮助......是否有什么可以将文本框的'格式'属性更改为常规数字?

4 个答案:

答案 0 :(得分:8)

您犯了一个错误||应该替换为&&,因此它会检查两个文本框是否都填充了值。

您错误地使用了.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();
 }

答案 1 :(得分:5)

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

此外,它应该是&&而不是||

至于你的错误,字符串的格式不正确,你会的    只要输入字符串不能,就可以使用任何不安全的代码    转换为 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所指出的那样,你只能使用一个事件处理程序,如本例所示。

答案 2 :(得分:0)

你可以这样做:

if(!string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text))

         { 

             textBox3.Text =convert.toString(Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text)).toString();
         }

答案 3 :(得分:0)

使用它。

    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)));
        }
    }
相关问题