- >输入字符串的格式不正确

时间:2013-06-21 00:07:07

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

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

 }

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

因为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

答案 2 :(得分: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();