C#WinForms - 自动添加两个文本框 [英] C# WinForms - Adding two textbox automatically
问题描述
我正在建立这三个文本框,如果填写了两个文本框,那么当我输入10 + 10时,将显示总和。结果是1010.有人可以帮我这个吗?
I'm building this three textbox where if the two textbox are filled the sum will be displayed however, when I input 10 + 10. The result is 1010. Can anbody help me with this?
这是我的代码:
public void textBoxTranspo_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBoxTranspo.Text) && !string.IsNullOrEmpty(textBoxDaily.Text))
textBoxTotalAmount.Text = (Convert.ToInt32(textBoxTranspo.Text) + Convert.ToInt32(textBoxDaily.Text).ToString());
}
public void textBoxDaily_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBoxTranspo.Text) && !string.IsNullOrEmpty(textBoxDaily.Text))
textBoxTotalAmount.Text = (Convert.ToInt32(textBoxTranspo.Text) + Convert.ToInt32(textBoxDaily.Text).ToString());
}
推荐答案
这是神奇的(多态性) ) +
运算符。如果操作数是数字类型(int,long,double),它将添加两个操作数的值,如果它们是字符串类型,甚至是一个字符串和第二个整数(就像你的情况一样),它将连接两个操作数。在您的情况下,转换后的 .ToString()
会产生问题。您将通过从该行中删除该结果来获得预期结果。
It is the magic(polymorphism) of the +
operator. it will add the values of two operands if the operands are of numeric types(int,long, double) and it will concatenate two operands if they are of type strings or even one string and second integer(as like in your case). Here in your case the .ToString()
after convert creates the issues. You will get the expected result by removing that from that line.
附加说明: Convert.ToInt32
将抛出 FormatException
如果输入文本不可转换,那么必须使用 int.TryParse
将文本转换为整数。所以代码看起来像这样:
An additional note : Convert.ToInt32
will throw FormatException
if the input text is not convertible, so use have to use int.TryParse
for converting text to integer. so the code will looks like this:
int intTranspo=0,intBoxDaily=0;
if(int.TryParse(textBoxTranspo.Text,out intTranspo) && int.TryParse(textBoxDaily.Text,out intBoxDaily))
textBoxTotalAmount.Text = (intTranspo + intBoxDaily).ToString();
这篇关于C#WinForms - 自动添加两个文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!