0

Im getting this error when i debug my program

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

public partial class Form1 : Form
{
     int newCount;
     int oldCount;

     private void timerGetData_Tick(object sender, EventArgs e)
     {
         string u = webBrowser1.DocumentText;
         u = u.Substring(u.IndexOf("<span id=\"PCoins\" class=\"Pcoins\""));
         u = u.Substring(u.IndexOf(">") + 1);
         u = u.Substring(0, u.IndexOf("</span>"));
         textBoxCoins.Text = u;

         newCount = Convert.ToDecimal(u);
         if (newCount <= oldCount)
         {
             textBoxNewCount.Text = "WON";
             oldCount = newCount;
         }
         else
         {
             oldCount = newCount;
             textBoxNewCount.Text = "LOSS";
         }
         timerGetData.Stop();
     }
}

The debugging is stopping at newCount = Convert.ToDecimal(u);

Can anyone help me?

Borys Verebskyi
  • 4,160
  • 6
  • 28
  • 42
Nohvok
  • 5
  • 3
  • And what is the value of `u` before `newCount = Convert.ToDecimal(u);`? Also, you'd better use something like http://stackoverflow.com/questions/846994/how-to-use-html-agility-pack to parse html. It is far less error-prone way, though a bit more heavy-weight. – Eugene Podskal Feb 27 '16 at 15:53
  • My u string is = 840.2449 directly from the webpage. – Nohvok Feb 27 '16 at 15:56
  • 2
    What is you locale setting? Converting a string in a decimal requires the string to be of the correct format for your locale settings unless you specify a CultureInfo parameters – Steve Feb 27 '16 at 15:57
  • By the way newCount is an integer, and you try to assign a decimal. This should never compile. You couldn't have this code with the exception you tell us. – Steve Feb 27 '16 at 16:03

2 Answers2

0

Well obviously u does not have a value that can be converted to decimal. You must trace your code to see why.

And change your variable types to decimal:

 decimal newCount;
 decimal oldCount;

insetead of

 int newCount;
 int oldCount;
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
0

If you are sure to have a string representing a valid value for a decimal then you should consider the locale settings of your machine. The conversion requires the string to be in the correct format for your locale if you don't specify the CultureInfo parameter.

If your string is in the Invariant culture like 840.2449 and your locale setting wants a comma as decimal separator then you need to specify the culture info

decimal newCount = 0;
string test = "840.2449";
newCount = Convert.ToDecimal(test, CultureInfo.InvariantCulture);
Console.WriteLine(newCount);

Of course your actual code never compiles because you cannot assign the return of Convert.ToDecimal to a variable of type integer. In my example I have changed the variable to the correct datatype.

Steve
  • 213,761
  • 22
  • 232
  • 286