user612865
user612865

Reputation:

int.Parse(textBox1.Text) error

I am getting error int pocet = int.Parse(textBox1.Text);

It says that data have some bad format, but I am writing only natural numbers to TextBox1

Upvotes: 0

Views: 5422

Answers (7)

txshon - Andy Tseng
txshon - Andy Tseng

Reputation: 33

I have the same problem.... make sure you use the right Cap number
9 and

the first one will work, and the second won't!

Hope this helps

@txshon

Upvotes: 0

iDurardz
iDurardz

Reputation: 1

Use this Method :

int pocet = Int32.Parse(TextBox1.Text.ToString());

Upvotes: 0

Mike Goatly
Mike Goatly

Reputation: 7518

I suspect you've either got an empty string there, there's whitespace at the start or end, or you're writing in the thousands separators.

You can instruct the Int32.Parse method to handle some of those cases like this:

Int32.Parse(
   "  -12,340  ",
   NumberStyles.AllowLeadingWhite |
   NumberStyles.AllowThousands |
   NumberStyles.AllowTrailingWhite |
   NumberStyles.AllowLeadingSign,
   CultureInfo.CurrentCulture));

Note the current culture bit at the end is important because the thousands separator will be different depending on the culture the user has their computer set to.

This still won't handle an empty string though - just check to see if the string is empty before doing the parsing.

Upvotes: 2

Leo
Leo

Reputation: 476

Try use

Convert.ToInt32(textBox1.Text);

Also debug to make sure you have only integer numbers in the textBox1.Text at conversion time.

Upvotes: 0

normalppl
normalppl

Reputation: 297

Try:

int intValueFromTbx = Convert.ToInt32(textBox1.Text)

Upvotes: 0

Nighil
Nighil

Reputation: 4129

if you using natural number then use

NumericUpDown Control

int pocet = int.Parse(numericUpDown1.Value.ToString());

Upvotes: 1

Darren Young
Darren Young

Reputation: 11090

I would probably use the TryParse method that will no throw an exception when there is bad data, but will allow you to use control flow and logic to handle it:

  int number;
  bool result = Int32.TryParse(TextBox.Text.Trim(), out number);
  if (result)
  {
     //Carry On/    
  }
  else
  {
     //Handle input error
  }

Upvotes: 2

Related Questions