0

I am trying to parse the retried value from the database into double, long, or integer, but it throws a FormatException. I need your help.

In this code, I am trying to retrieve hours from the database and sum them to calculate total hours input into the database.

String hrs;
Double resultHrs=0;

while (oleDbDataReader1.Read())
{
    hrs = oleDbDataReader1["Hours"].ToString();
    double HRS = double.Parse(oleDbDataReader1["Hours"].ToString());
    resultHrs = resultHrs + HRS;
}// end while
Joe Mastey
  • 26,809
  • 13
  • 80
  • 104
Abeer Islam
  • 33
  • 1
  • 2
  • 7

2 Answers2

2

Don't do the string conversion in the first place:

double hours = (double) oleDbDataReader1["Hours"];

Unless your value is actually a string in the database (in which case you should fix that) there's no reason to convert it into a string. (If it's not a type mapped to double, you should change what you cast it to, of course.)

EDIT: If it's non-numeric in the database, then you probably do need to use double.Parse - but you might want to specify the culture. For example, assuming they're all of the form "10.2" rather than "10,2" (as some cultures would use) you would want something like:

double hours = double.Parse((string) oleDbDataReader1["Hours"],
                            CultureInfo.InvariantCulture);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

I use:

 HRS = oledbDataReader1.GetDouble(iColumn);

where iColumn is the column index in the query

Kzest
  • 526
  • 3
  • 4