1

In SQL Server I have a db column named AppZip with type int. I have a textbox with a 5 digit zip code. When i try to save I get an error "Input string was in incorrect format." I'm confused. I'm converting the string representation of "12345" to int type, how is it the wrong format for the database? Here's my code.

q.AppZip =Convert.ToInt32(txtAppZip.Text);

(I'm using linq to sql...)

EDIT: It was because I didn't stop the method that populates the field on page load from executing on post back.

3 Answers 3

2

The exception is being thrown by the Convert.ToInt32(). Check whether the Text property is in correct format and Trim() the property before you pass it to Convert.ToInt32().

string appZipText = txtAppZip.Text.Trim();
if (!string.IsNullOrEmpty(appZipText))
{
    q.AppZip = Convert.ToInt32(appZipText);
}

Additionally, you can also use Int32.TryParse() to check the validity of the string before you convert.

int appZip;
string appZipText = txtAppZip.Text.Trim();

if(!string.IsNullOrEmpty(appZipText) &&
    Int32.TryParse(appZipText.Trim(),NumberStyles.Integer,CultureInfo.CurrentCulture, out appZip))
{
   // Valid format
   // Use or assign converted value
   q.AppZip = appZip;
}
else 
{
   // Cannot convert to Int32
}


More information

Sign up to request clarification or add additional context in comments.

Comments

0

Check the mappings of all the columns in your table definition. It could be one of the other columns in the table throwing the error. Run up SQL Profiler to check the SQL that is generated.

Comments

-1

The only way to raise the FormatException is concating some unconvertible character to the original string.

Make sure you didnt type anything char by mistake and try again, thats the only reasonable explanation i can see now

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.