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

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

@AbeerIslam: Why is it text at all, if it's always meant to hold a number?
I had to cast it anyway while inputting the value into the database that was my reason for doing that however i have changed it anyway
1

I use:

 HRS = oledbDataReader1.GetDouble(iColumn);

where iColumn is the column index in the query

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.