0
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);

 }
4

3 回答 3

0

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

于 2013-06-21T00:14:43.747 回答
0

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

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();
于 2013-06-21T03:59:41.387 回答
0

它抛出一个错误,因为 ProductPrice 无法转换为十进制,这意味着它的格式不正确。打开你的调试器并确保你有一个有效的字符串来解析。

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
于 2013-06-21T00:39:38.493 回答