6

我的表单有一个包含数量数字的文本框。然后在 textchanged 事件中,该数字被放置在带有货币值的标签的文本属性中(例如:4.00 美元)。在我的按钮单击事件中,我试图添加标签中的所有值。使用以下代码时,tryparse 每次都失败

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

但是如果我使用文本框的 text 属性尝试同样的事情,它就可以工作。

int num2;
if (int.TryParse(txt85x11bw.Text, out num2)) 
{
     MessageBox.Show(num2.ToString());
}
else
{
      MessageBox.Show("it failed");
 }
4

3 回答 3

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);
于 2015-01-28T18:57:12.957 回答
6

尝试

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

反而。您要解析的数字是:

  • 不是整数
  • 包含货币符号
于 2013-03-13T19:34:01.453 回答
0

Use NumberStyles.Currency instead of NumberStyles.AllowCurrencySymbol

See How to parse string to decimal with currency symbol?

于 2017-10-03T05:56:28.190 回答