An exception; An exception of type "System.FormatException" occurred in mscorlib.ni.dll, but was not processed in the user code

Hi, I have an application for Windows Phone 8. I have an exception.

An exception of type "System.FormatException" occurred in mscorlib.ni.dll, but was not processed in the user code

Here is the code

private void Button_Click_1(object sender, RoutedEventArgs e) { double basestolen; double attempedstales; double avarege; double putout; if (puttext.Text.Length == 0 | basetext.Text.Length==0 ) { MessageBox.Show(" Enter Values for Base Stolen and Putouts "); } basestolen = Convert.ToDouble(basetext.Text); putout = Convert.ToDouble(puttext.Text); attempedstales = basestolen + putout; if (attempedstales != 0 ) { avarege = (((basestolen / attempedstales) / 100)); avarege = avarege * 10000; avgtext.Text = Convert.ToString(avarege); } else { MessageBox.Show("Attemped Stales Value should not be Zero"); } } 

Running the application and if I do not enter the value in the text fields, it returns the msg field, but after that the application will stop and return the checkout above? what is the problem?

+4
source share
2 answers

Most likely the error is here:

 basestolen = Convert.ToDouble(basetext.Text); putout = Convert.ToDouble(puttext.Text); 

It throws a FormatException if the number does not match a valid one. ( see details here ). Try using double.TryParse to safely parse your values.

 double result; bool success = double.TryParse(basetext.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out result); 
+3
source

You forgot to stop executing your method after displaying a message box:

 if (puttext.Text.Length == 0 || basetext.Text.Length==0 ) { MessageBox.Show(" Enter Values for Base Stolen and Putouts "); return; } 

In addition, when converting strings to double, be sure to specify the culture. The Windows Phone application will be run by users around the world, and some countries use different decimal separators. For instance:

 basestolen = Convert.ToDouble(basetext.Text, CultureInfo.InvariantCulture); 
0
source

Source: https://habr.com/ru/post/1482961/


All Articles