开发者

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 na开发者_C百科tural numbers to TextBox1


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.


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
  }


if you using natural number then use

NumericUpDown Control

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


Try:

int intValueFromTbx = Convert.ToInt32(textBox1.Text)


Try use

Convert.ToInt32(textBox1.Text);

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


Use this Method :

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜