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

问题描述 投票:0回答:4

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

请帮忙...有什么办法可以将文本框的“格式”属性更改为一般数字吗?

c# winforms textbox
4个回答
11
投票

您犯了一个错误

||
应替换为
&&
,以便它会检查两个文本框是否都填充了值。

您错误地使用了

.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();
 }

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 指出的那样,您只能使用一个事件处理程序,如本例所示。


0
投票

你可以这样做:

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

         { 

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

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)));
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.