Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net

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

Mobileno = Convert.ToInt32(txmobileno.Text);

error i amm getting while inserting in to database

like image 628
vignesh Avatar asked Jun 14 '11 07:06

vignesh


3 Answers

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.

like image 162
Oded Avatar answered Sep 21 '22 08:09

Oded


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.

like image 44
GvS Avatar answered Sep 18 '22 08:09

GvS


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.
like image 26
MattDavey Avatar answered Sep 21 '22 08:09

MattDavey