-2

I get the error: 'Input string was not in a correct format'..... I am running an if else calculation and then populating a label with the result the variable is declared as decimal then ToString('C') to the label...

List<string> moneyWon = new List<string>();

     private void calculateAmountWon()
     {
         moneyWon.Add(amountWonlabel.Text);

         decimal won = moneyWon.Sum(str => Convert.ToInt32(str));             

         moneyWonLabel.Text = won.ToString("C");
      }

    private void button2_Click(object sender, EventArgs e)
    {
        this.Close();
    }
4

2 回答 2

1

唯一会引发该错误的是Convert.ToInt32(str)调用。列表中的moneyWon一项不是有效值int

您可能还应该声明moneyWon为 aList<int>并将所有值存储为int's 而不是string's。将所有内容存储为字符串然后int在需要时将其转换为没有意义。

于 2014-10-28T22:20:51.167 回答
0

根据您输出的内容,我假设您的字符串被格式化为带有货币符号和两位小数的货币。如果是这种情况,您可以将解析更改为:

decimal won = moneyWon.Sum(str => decimal.Parse(str, NumberStyles.Currency));

您仍然容易受到无效格式的影响,但如果这些值都是以编程方式设置的,那么它们应该是可预测的。

另一种选择是使用数字类型列表并预先解析:

List<decimal> moneyWon = new List<decimal>();

private void calculateAmountWon()
{
     moneyWon.Add(decimal.Parse(amountWonlabel.Text, NumberStyles.Currency));

     decimal won = moneyWon.Sum();             

     moneyWonLabel.Text = won.ToString("C");
}
于 2014-10-28T22:22:45.813 回答