0

我正在尝试获取textBox19数字 (9,2) 的结果,例如17050.00并从中减去120textBox20等数字的值。所以17050.00 - 120

我试图做到这一点:

textBox21.Text = (Convert.ToDouble(textBox19.Text) - 
Convert.ToDouble(textBox20.Text)).ToString();

它应该这样做:它应该减去 textBox19 - textBox20。并在 textBox21 中显示结果。

确实如此:但是当我调试时 intextBox19仍然是17050.00而 intextBox20120。我想显示结果textBox21.Text

这行代码给了我这个异常:Input string was not in correct format.当我将 textBox19 中的值从17050.00 更改为* 17050* 时,程序会继续运行并且不会下降。

请问我哪里出错了?

4

2 回答 2

1

首先,这两个值看起来不应该存储在double. 它们看起来像应该以小数形式存储的货币值。

将您的代码重写为以下内容:

decimal textBox19Value; //Needs a better name
decimal textBox20Value; //Needs a better name

if (!decimal.TryParse(textBox19.Text, out textBox19Value))
{
    // textBox19 doesn't contain a valid decimal
    // present error to user and return
}

if (!decimal.TryParse(textBox20.Text, out textBox20Value))
{
    // textBox20 doesn't contain a valid decimal
    // present error to user and return
}

decimal result = textBox19Value + textBox20Value;

textBox21.Text = result;
于 2013-07-22T15:54:03.813 回答
1

@Tobsey 提供了我要采取的方法,但你的问题有些含糊,所以我要投入 2 美分。

我不知道你在做什么来设置 textBox21 的值,例如单击一个按钮等,但我只是打算使用 TextChanged 事件。

在我的FormName .Designer.cs 中,我在 InitializeComponent() 中有以下几行:

this.TextBox19.TextChanged += new System.EventHandler(this.ChangeValue);
this.TextBox20.TextChanged += new System.EventHandler(this.ChangeValue);

在实际的FormName .cs 文件中,我有以下内容:

private void ChangeValue(object sender, EventArgs e)
{
    double text20, text19;
    if (
        !double.TryParse(TextBox19.Text, out text19) ||
        !double.TryParse(TextBox20.Text, out text20)
    )
    {
        TextBox21.Text = "Can't calculate.";
        return;
    }

    TextBox21.Text = ( text19 - text20 ).ToString();
}

至于你为什么得到FormatException Input string was not in correct format.,我不能告诉你。也许存在本地化问题,在这种情况下,您将不得不修改TryParse上述内容以使用正确的文化格式以及 ToString()。在 MSDN 上查找“格式类型”,因为我只能发布 2 个链接。这是我在测试中尝试 17050.00 和 17050 时首先想到的,没有任何问题。

于 2013-07-22T16:26:59.157 回答