【问题标题】:-->Input String was not in correct format-->输入字符串格式不正确
【发布时间】:2013-06-21 00:07:07
【问题描述】:
if (!blnMatch)
 {
     DataRow shoppingCartDataRow;

     shoppingCartDataRow = shoppingCartDataTable.NewRow();
     shoppingCartDataRow["ProductID"] = int.Parse(productid1);
     shoppingCartDataRow["Quantity"] = 1;
     shoppingCartDataRow["ProductName"] = ProductName;
     shoppingCartDataRow["ProductPrice"] = decimal.Parse(ProductPrice); 
     //-->Input String was not in correct format..Why is the input string for price not in correct format?

     shoppingCartDataTable.Rows.Add(shoppingCartDataRow);

 }

【问题讨论】:

  • ProductPrice的值是多少?
  • ProductPrice 是一个字符串吗?尝试单步执行代码并在执行 decimal.Parse 之前检查 ProductPrice 的值。

标签: asp.net ado.net shopping-cart


【解决方案1】:

如果ProductPrice 的值无法转换为小数(例如,如果有字母),就会发生这种情况。检查ProductPrice 的值是否是十进制数的合理值。

【讨论】:

    【解决方案2】:

    由于 ProductPrice 无法转换为 Decimal,因此引发错误,这意味着它的格式不正确。打开你的调试器并确保你有一个有效的字符串来解析。

    http://msdn.microsoft.com/en-us/library/system.decimal.parse.aspx

    您可以使用TryParse添加一些验证

    decimal convertedProductPrice;
    if(decimal.TryParse(ProductPrice, out convertedProductPrice))
      shoppingCartDataRow["ProductPrice"] = convertedProductPrice;
    else
      shoppingCartDataRow["ProductPrice"] = 0;//assign a default value on failure
    

    【讨论】:

      【解决方案3】:

      您可以创建一个扩展方法来检查这一点,如下所示。

      public static class Extensions
      {
          public static decimal ToCurrency(this object value)
          {
              const NumberStyles style = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands
                                         | NumberStyles.AllowParentheses | NumberStyles.AllowLeadingSign
                                         | NumberStyles.AllowCurrencySymbol;
      
              CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");
              decimal tempValue;
              decimal.TryParse(value as string, style, culture, out tempValue);
              return tempValue;
          }
      }
      
      
      shoppingCartDataRow["ProductPrice"] = ProductPrice.ToCurrency();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-23
        • 2013-08-22
        相关资源
        最近更新 更多