Value was either too large or too small for an Int32 [duplicate]

匿名 (未验证) 提交于 2019-12-03 01:31:01

问题:

Possible Duplicate:
What is the maximum value for a int32?

Mobileno = Convert.ToInt32(txmobileno.Text); 

error i amm getting while inserting in to database

回答1:

Why on earth would you use an integer of any type to store a phone number?

You can't meaningfully do any arithmetics on one and you lose all leading zeroes.

Use a string instead.



回答2:

An integer (Int32) is limited in the values it can store since it "only" uses 32 bits. It can store a value between 2,147,483,647 and -2,147,483,648. (More information on MSDN)

The value represented by the txmobileno.Text, is too large or too small.

Looking at the name txmobileno is probably a mobile phone number. This kind of numbers have too much digits to store in an int32. Also a phone number tends to start with a 0 or 00 or + (international). There's no way of storing this kind of information in an integer (or another number type). Just store them in a string.



回答3:

As others have pointed out, storing a phone number as an integer is a mistake.

  • You lose the ability to store characters and whitespace, for example country codes - "+44 (0800) 12345".
  • There is no logical reason to store it as an integer - would you ever need to do arithmetic on two telephone numbers? Does it make sense to add two phone numbers together?
  • Leading zeros will be lost - (0800 12345) will become (80012345).
  • Storing it as a string allows you to do regex validation on the user input.

Having said that, the original question does raise some points which should be made:

  • Prefer Int32.TryParse instead of Convert.ToInt32 when the source value is a string.
  • When dealing with values which may potentially overflow - enclose the code in a checked { ... } block.


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!