-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();
    }
BartoszKP
  • 34,786
  • 15
  • 102
  • 130
ghowell
  • 5
  • 3

2 Answers2

1

The only thing that will throw that error is the Convert.ToInt32(str) call. One of the items in the moneyWon list is not a valid int value.

You should probably also declare moneyWon as a List<int> and store all the values as int's instead of string's. It doesn't make sense to store everything as a string and then convert it to int when you need it.

Dave Zych
  • 21,581
  • 7
  • 51
  • 66
0

Based on what you're outputting I'm assuming that your strings are formatted as currency with a currency symbol and two decimal places. If that's the case you can change your parsing to:

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

You're still vulnerable to invalid formats but if the values are all set programatically then they should be predictable.

Another option is to use a list of numeric types and parse up front:

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");
}
D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • Having some trouble with the NumberStyles.Currency... I am working in Visual Studio Express 2012.... don't know if that matters or if it is a using problem... – ghowell Oct 28 '14 at 23:28
  • @ghowell Add `using System.Globalization` to the top of your class file. – D Stanley Oct 29 '14 at 12:43
  • D Stanley - Yes, That fixed it! I like your solution because it lets me keep the Currency format on the label I am pulling from. Thanks for the lesson!! – ghowell Oct 29 '14 at 18:49