Input string was not in a correct format

R

r

Hi,
I am poulating a textbox with a number from a db, based on
the current cultrue:

textBox1.Text =
String.Format(Thread.CurrentThread.CurrentCulture,"{0:###,###,###}",number);

Now, the number has the value: 9999, and it is shown as
9,999.
When I try to parse it:

int y = int.Parse(textBox1.Text,Thread.CurrentThread.CurrentCulture);

It gives me the "Input string was not in a correct format".

Any ideas?

Thanks in advance.
 
W

Wessel Troost

9,999.
When I try to parse it:

int y = int.Parse(textBox1.Text,Thread.CurrentThread.CurrentCulture);

It gives me the "Input string was not in a correct format".
By default, int.Parse() uses the number style "integer", which does not
allow for grouping. Grouping is allowed by default for the number style
"number". See the following example:

CultureInfo Info = new CultureInfo("en-us");
int i;
// Exception
i = int.Parse( "9,999", Info.NumberFormat );
// Same exception
i = int.Parse( "9,999", NumberStyles.Integer, Info.NumberFormat );
// This works; number style allows for grouping
i = int.Parse( "9,999", NumberStyles.Number, Info.NumberFormat );

Greetings,
Wessel
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

It's because the "," in the number is not understod , you have two options,
either you use InvariantCulture to display the number or you just "parse"
the number back fmro the textbox, this latter solution is what I would go
for.

cheers,
 
O

orekinbck

I was just about to post when I noticed Wessel's answer. Pretty much
exactly what I was going to say except two minor things:
(1) This would also work:
i = int.Parse("9,999", NumberStyles.Number)
(2) But as Wessel has demonstrated it is better practice to include
CultureInfo. You can get the user's culture through
CultureInfo.CurrentCulture:
i = int.Parse("9,999",
NumberStyles.Number,CultureInfo.CurrentCulture);

Also, remember to add reference to System.Globalization

Cheers
Bill
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top