Click here to Skip to main content
15,498,797 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:

I am trying to convert a string array to int array using the following code:
stringArray[i, 0] = (Reader["Test"].ToString());
stringArray[i, 1] = (Reader["Test1"].ToString());
stringArray[i, 2] = (Reader["Test2"].ToString());

int toInt0 = Int32.Parse(stringArray[i, 0]);
int toInt1 = Int32.Parse(stringArray[i, 1]);
int toInt2 = Int32.Parse(stringArray[i, 2]);

intArray[i, 0] = toInt0;
intArray[i, 1] = toInt1;
intArray[i, 2] = toInt2;

I get the following error:

System.FormatException: Input string was not in a correct format.
at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
at System.Int32.Parse(String s)
at Book.button1.test() in C:\Users\Dave\Documents\Visual Studio 2010\Projects\Book\Form1.cs:line 603 Exception caught.

What should i fix ?


1 solution

This is expected; your code is correct.
This what it is: string in not in correct format.

If the argument of Parse is "-33321", it will return correspondent integer value, if it is "blah-blah", what else could you expect? Don't use TryParse, keep it as it is now in your code, use debugger and find where "blah-blah" gets in your string array.

If you still need help, ask a follow-up question, but show you data and the code writing your string, not converting into integers.

Important! Please don't post it as a Question (a common mistake), use "Improve Answer", in other cases, use "Add comment".

Share this answer
Espen Harlinn 20-Feb-11 16:32pm    
My 5 - "how OP could expect to turn "Test", "Test1" and "Test2" into integers baffles me" - oops - a bit of too fast, and inaccurate, reading on my part, sorry :)
Sergey Alexandrovich Kryukov 20-Feb-11 16:48pm     CRLF
Exactly (actually, we don't know the string, but anyway...). Thank you, Espen, --SA
Nish Nishant 20-Feb-11 17:32pm    
Espen, he's not converting "Test" but Reader["Test"].
Sergey Alexandrovich Kryukov 20-Feb-11 17:36pm     CRLF
Ah, yes! That's correct, but probably does not make the string better :-) --SA
Espen Harlinn 20-Feb-11 17:52pm    
Probably a good thing I didn't answer this one :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900