HMc*_*eak 3 c# textbox winforms
我已尝试将此代码从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());
}
}
Run Code Online (Sandbox Code Playgroud)
请帮助...有没有什么比将文本框的'格式'属性更改为一般数字?
你犯了一个错误||应该被替换,&&所以它会检查两个文本框都填充了值.
您已经.ToString()错误地使用了方法,仅适用于textbox2,请正确检查括号.
textBox3.Text = (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text).ToString());
Run Code Online (Sandbox Code Playgroud)
应该
textBox3.Text = (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text)).ToString());
Run Code Online (Sandbox Code Playgroud)
试试这个经过测试的代码.
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();
}
Run Code Online (Sandbox Code Playgroud)
您当前的表达式在您的条件的第二部分中缺少否定(!)
此外,它应该是&&不是||
至于你的错误,字符串的格式不正确,只要输入字符串无法转换为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();
}
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,就像Glenn指出的那样,你只能使用一个事件处理程序,就像这个例子中一样.