I have a little problem with ASP.NET and C#. This is my error code:
An exception of type ‘System.FormatException’ occurred in mscorlib.dll but was not handled in >user code
Additional information: Input string was not in a correct format.
protected void Page_Load(object sender, EventArgs e)
{
if(this.IsPostBack == false)
{
Currency.Items.Add(new ListItem("Euro", "0.85"));
Currency.Items.Add(new ListItem("Yen", "11.30"));
Currency.Items.Add(new ListItem("PLN", "4.20"));
Currency.Items.Add(new ListItem("GBP", "5.62"));
}
}
protected void Convert_Click(object sender, EventArgs e)
{
decimal oldAmount;
bool succes = Decimal.TryParse(TextBox.Value, out oldAmount);
if(succes)
{
ListItem item = Currency.Items[Currency.SelectedIndex];
decimal newAmount = oldAmount * decimal.Parse(item.Value);
Result.InnerText = "Result: " + newAmount;
}
}
I tried Decimal.Parse, Decimal.TryParse and other strange combinations. Now I’m sure that issue is with strings and parsing them to decimal. When I created String variable – there was that same error while parsing. So can someone tell me what to do to be able to convert String to decimal?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Try using “0,85” instead of “0.85”. I think you can use the dot decimal if you change culture.
Here is some more information:
How to change symbol for decimal point in double.ToString()?
Method 2
Please try with the below code snippet.
CultureInfo info = CultureInfo.GetCultureInfo("es-ES");
string storedValue = "3,85";
decimal oldAmount;
bool succes = Decimal.TryParse(storedValue, NumberStyles.Any, info, out oldAmount);
Method 3
Use TextBox.Text instead:
bool succes = Decimal.TryParse(TextBox.Text, out oldAmount);
Method 4
TextBox.value is wrong. YourTextBox.Text is correct…!
bool success = Decimal.TryParse(TextBox.Text, out oldAmount);
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0