Tuesday, March 06, 2007

Currency formatting issue ASP.NET, FormView*

Tuesday, March 06, 2007 1:17:23 AM (GMT Standard Time, UTC+00:00)

Quick post on an error I was getting for the last hour that has made my night somewhat of a rush! This is related to ASP.NET 2, VS'05, FormView, ObjectDataSource, applying Data formats to fields.

I was trying to delete a record using a FormView and I kept getting the following error, "Input string was not in a correct format."

As I reviewed the stack trace I saw the following:

System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) +2752771
System.Number.ParseDecimal(String value, NumberStyles options, NumberFormatInfo numfmt) +119
System.Decimal.Parse(String s, NumberStyles style, IFormatProvider provider) +37
System.Convert.ToDecimal(String value, IFormatProvider provider) +50

So naturally, I figured it must be a conversion problem (from String to Number). Possibly a string that I have in the form being converted to a number (int or decimal) before being passed to the database. Since I only had one int/decimal I was dealing with in this form, it was easy to find.. - it was a currency field.

Now I had formatted this currency field using "<%# Bind("price", "{0:C}") %>", or more specifically {0:C} for currency (it renders the amount with a "$" sign prefixed). As I investigated some more, I recognised that the problem here was that the entire "$<number>" was being passed to the procedure.. therefore when the attempt was made to convert it to a number to send it to the DB, it failed as "$" can't be converted.

To avoid this problem, you can do two things, forget about the {0:C} formatting... which is really not an option (as it is always nice to show the currency sign), Or in the FormView1_ItemDeleting event, simply remove the "$" from the parameter. (Remember this event is called before the parameters are passed.)

I honestly believe there should be some other way to do this though, so I'll look into it a bit. This thing really should not be an issue.

Related posts:
Select a random row in MS SQL...
Regular expressions
VS2005, ASP.NET 2 & DLLs, DLLs..
MS's ASP.NET and.. PHP
2-way databinding cascading drop down lists within a FormView
ApplicationName Property when customising providers

Comments are closed.