0

我不断收到输入字符串格式不正确的错误。我不知道为什么会这样。我正在尝试写入我的数据库,邮政编码是一个数字。我尝试将其更改为字符串,但这会导致在执行非查询时缺少参数。

Input string was not in a correct format.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.FormatException: Input string was not in a correct format.

Source Error: 


Line 130:               param.DbType = DbType.Int32;
Line 131:               param.Direction = ParameterDirection.Input;
Line 132:               param.Value = Int32.Parse(shipZipCodeTxt.Text);
Line 133:                       
Line 134:               comm.Parameters.Add(param); 

Source File:     Line: 132 

Stack Trace: 


[FormatException: Input string was not in a correct format.]
   System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) +7472247
   System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) +119
   System.Int32.Parse(String s) +23
   ASP.finals_signup_aspx.SubmitForm(Object sender, EventArgs e) in e:\ectserver\ADELEO10\finals\signup.aspx:132
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +111
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +110
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565
4

1 回答 1

10

例外很明显,文本框包含无法被解析例程排除且不可转换为整数的字符

您可以尝试使用

int result;
if(Int32.TryParse(shipZipCodeTxt.Text, out result))
    param.Value = result;
else
    Response.Write("Please type a numeric value");

至少这种方法会避免异常。

另一种可能性是您的 aspx 标记的RangeValidator控件

<asp:RangeValidator id="RangeValidator1" runat="server" 
     ControlToValidate="shipZipCodeTxt" Type="Integer"
     ErrorMessage="Please type a valid zip code">
     MaximumValue="999999999" MinimumValue="0"
</asp:RangeValidator>

并且您还可以添加一个 RequiredFieldValidator 以避免空条目

<asp:RequiredFieldValidator id="RequiredFieldValidator1"  
  runat="server" ErrorMessage="Please type a zip code" 
  ControlToValidate="shipZipCodeTxt" 
</asp:RequiredFieldValidator>
于 2013-06-08T22:25:58.857 回答