开发者

Input string was in incorrect format error when saving to database

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 s开发者_JS百科tring 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.


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

  • Int32.Parse Method (String, NumberStyles, IFormatProvider)
  • Convert.ToInt32 Method (String)


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.


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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜