6

My form has textbox that holds a number for quantity. then in the textchanged event that number is placed in a label's text property with currency value (ex: $4.00). In my button click event I am trying to add all the values from the labels. When using the following code tryparse fails everytime

int num1;
string text = lbl85x11bwsub.Text;
if (int.TryParse(text, out num1)) 
{
     MessageBox.Show(num1.ToString()); //testing
}
else
{
      MessageBox.Show("it failed");
}

but if I try the same thing using the textbox's text property it works.

int num2;
if (int.TryParse(txt85x11bw.Text, out num2)) 
{
     MessageBox.Show(num2.ToString());
}
else
{
      MessageBox.Show("it failed");
 }
KFP
  • 699
  • 3
  • 12
  • 33

3 Answers3

14

@Frederik Gheysels give you almost complete answer on your question except one tiny thing. In this case you should use NumberStyles.Currency because your number can be not only not integer, but also contain thousand and decimal separators. While NumberStyles.AllowCurrencySymbol will only care about currency sign. On the other hand NumberStyles.Currency is a composite number style. Which can allow almost all the other separators.

So, this expression, probably, will works:

Decimal.TryParse(text, 
    NumberStyles.Currency, 
    CultureInfo.CurrentCulture, 
    out result);
apros
  • 2,848
  • 3
  • 27
  • 31
6

Try

Decimal.TryParse(text, 
    NumberStyles.Currency, 
    CultureInfo.CurrentCulture, 
    out result);

instead. The number you're trying to parse, is:

  • not an integer
  • contains a currency symbol
Frederik Gheysels
  • 56,135
  • 11
  • 101
  • 154
  • what happens when you leave out the currency symbol from your string ? Are you sure that the currency symbol that is present in the string, is the actual currency symbol defined in your culture settings ? ... (Debugging 101) – Frederik Gheysels Mar 13 '13 at 20:19
0

Use NumberStyles.Currency instead of NumberStyles.AllowCurrencySymbol

See How to parse string to decimal with currency symbol?

ryan.c
  • 244
  • 1
  • 6