System.FormatException:输入字符串的格式不正确

时间:2012-04-21 00:46:15

标签: asp.net vb.net

所以我试着为我的单一课程做一个小型网上商店,我偶然发现了这个我不明白的错误。首先,这是我的订单页面的代码。

<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)  

        Dim strSessionID As String
        Dim strItem As String
        Dim strQuantity As String
        strSessionID = Session.SessionID
        strItem = Session("Item")
        strQuantity = Session("Quantity")
        tbxItem.Text = strItem
        tbxQuantity.Text = strQuantity

    End sub

    Protected Sub btnAddOrder_Click(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim strItem As String
        Dim strQuantity As String
        Dim strFullName As String
        Dim strAddressLine As String
        Dim intPhoneNumber As Integer
        Dim intCardNumber As Integer
        Dim strNameOnCard As String
        Dim strExpirationDate As String

        strItem = tbxItem.Text
        strQuantity = tbxQuantity.Text
        strFullName = tbxFullName.Text
        strAddressLine = tbxAddressLine.Text
        intPhoneNumber = tbxPhoneNumber.Text
        intCardNumber = tbxCardNumber.Text
        strNameOnCard = tbxNameOnCard.Text
        strExpirationDate = tbxExpirationDate.Text

        Dim strDatabaseNameAndLocation As String
        strDatabaseNameAndLocation = Server.MapPath("pcland.mdb")
        Dim strSQLCommand As String
        strSQLCommand = "INSERT INTO orders(Item, Quantity, FullName, AddressLine, PhoneNumber, CardNumber, NameOnCard, ExpirationDate) " & _
            "Values ('" & strItem & "','" & strQuantity & "','" & strFullName & "', '" & strAddressLine & "', '" & intPhoneNumber & "', '" & intCardNumber & "', '" & strNameOnCard & "', '" & strExpirationDate & "');"
        Dim objOleDbConnection As System.Data.OleDb.OleDbConnection
        objOleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation)
        objOleDbConnection.Open()
        Dim objOleDbCommand As System.Data.OleDb.OleDbCommand
        objOleDbCommand = New System.Data.OleDb.OleDbCommand(strSQLCommand, objOleDbConnection)
        objOleDbCommand.ExecuteNonQuery()
        objOleDbConnection.Close()        
        strSQLCommand = "SELECT orders.* FROM orders ORDER BY orders.Price DESC;"
        objOleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation)       
        tbxItem.Text = ""
        tbxQuantity.Text = ""
        tbxFullName.Text = ""
        tbxAddressLine.Text = ""
        tbxPhoneNumber.Text = ""
        tbxCardNumber.Text = ""
        tbxNameOnCard.Text = ""
        tbxExpirationDate.Text = ""

        lblConfirmationMessage.Text = "Thank you for order."

    End Sub

</script>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>PC land | Cart</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <link href="#" rel="stylesheet" type="text/css" />
    </head>
    <body>
        <form id="webform" runat="server">
            <div>
                <table border="0">
                <tr>
                    <td>Item:</td>
                    <td><asp:TextBox ID="tbxItem" ReadOnly="True" runat="server"></asp:TextBox></td>
                </tr>
                <tr>
                    <td>Quantity:</td>
                    <td><asp:TextBox ID="tbxQuantity" ReadOnly="True" runat="server"></asp:TextBox></td>
                </tr>
                <tr>
                    <td>Full Name:</td>
                    <td><asp:TextBox ID="tbxFullName" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfvFullName" runat="server" ControlToValidate="tbxFullName" 
                    Display="Dynamic">You must enter your full name</asp:RequiredFieldValidator></td>
                </tr>
                <tr>
                    <td>Address Line:</td>
                    <td><asp:TextBox ID="tbxAddressLine" TextMode="MultiLine" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfvAddressLine" runat="server" ControlToValidate="tbxAddressLine" 
                    Display="Dynamic">You must enter your address</asp:RequiredFieldValidator></td>
                </tr>
                    <td>Phone Number:</td>
                    <td><asp:TextBox ID="tbxPhoneNumber" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfvPhoneNumber" runat="server" ControlToValidate="tbxPhoneNumber" 
                    Display="Dynamic">You must enter your phone number (No spaces or dashs)</asp:RequiredFieldValidator></td>
                </tr>
                    <td>Card Number:</td>
                    <td><asp:TextBox ID="tbxCardNumber" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfvCardNumber" runat="server" ControlToValidate="tbxCardNumber" 
                    Display="Dynamic">You must enter the card number (No spaces or dashs)</asp:RequiredFieldValidator></td>
                </tr>
                    <td>Name On Card:</td>
                    <td><asp:TextBox ID="tbxNameOnCard" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfvNameOnCard" runat="server" ControlToValidate="tbxNameOnCard" 
                    Display="Dynamic">You must enter the full name that is on the card </asp:RequiredFieldValidator></td>
                </tr>
                    <td>Expiration Date:</td>
                    <td><asp:TextBox ID="tbxExpirationDate" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfvExpirationDate" runat="server" ControlToValidate="tbxExpirationDate" 
                    Display="Dynamic">You must enter the expiration date (Example format: 01/02/90)</asp:RequiredFieldValidator></td>
                </tr>
                <tr>
                    <td><asp:Button id="btnAddRecord" runat="server" onclick="btnAddOrder_Click" postbackurl="confirm.aspx" text="Submit" /></td><br />
                </tr>
                </table>
                <asp:Label ID="lblConfirmationMessage" runat="server"></asp:Label><br />
            </div>
        </form>
        <div id="footer">Copyright &copy; 2012 PC Land - All Rights Reserved</div>
    </body>
</html>

现在,这里是确认页面的代码,该页面应显示用户在订单页面上选择的选项

<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim tbxItem As TextBox
        Dim tbxQuantity As TextBox
        Dim tbxFullName As TextBox
        Dim tbxAddressLine As TextBox
        Dim tbxPhoneNumber As TextBox
        Dim tbxCardNumber As TextBox
        Dim tbxNameOnCard As TextBox
        Dim tbxExpirationDate As TextBox

        Dim strItem As String
        Dim strQuantity As String
        Dim strFullName As String
        Dim strAddressLine As String
        Dim intPhoneNumber As Integer
        Dim intCardNumber As Integer
        Dim strNameOnCard As String
        Dim strExpirationDate As String


        tbxItem = CType(Me.PreviousPage.FindControl("tbxItem"), TextBox)
        tbxQuantity = CType(Me.PreviousPage.FindControl("tbxQuantity"), TextBox)
        tbxFullName = CType(Me.PreviousPage.FindControl("tbxFullName"), TextBox)
        tbxAddressLine = CType(Me.PreviousPage.FindControl("tbxAddressLine"), TextBox)
        tbxPhoneNumber = CType(Me.PreviousPage.FindControl("tbxPhoneNumber"), TextBox)
        tbxCardNumber = CType(Me.PreviousPage.FindControl("tbxCardNumber"), TextBox)
        tbxNameOnCard = CType(Me.PreviousPage.FindControl("tbxNameOnCard"), TextBox)
        tbxExpirationDate = CType(Me.PreviousPage.FindControl("tbxExpirationDate"), TextBox)

        strItem = tbxItem.Text
        strQuantity = tbxQuantity.Text
        strFullName = tbxFullName.Text
        strAddressLine = tbxAddressLine.Text
        intPhoneNumber = tbxPhoneNumber.Text
        intCardNumber = tbxCardNumber.Text
        strNameOnCard = tbxNameOnCard.Text
        strExpirationDate = tbxExpirationDate.Text

        lblItem.Text = "You said your item was " & strItem
        lblQuantity.Text = "You said your quantity was " & strQuantity
        lblFullName.Text = "You said your full Name was " & strFullName
        lblAddressLine.Text = "You said your Address was " & strAddressLine
        lblPhoneNumber.Text = "You said your item was " & intPhoneNumber
        lblCardNumber.Text = "You said your item was " & intCardNumber
        lblNameOnCard.Text = "You said the name on your card was " & strNameOnCard
        lblExpirationDate.Text = "You said the expiration date was " & strExpirationDate

    End Sub

</script>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>PC land | Cart</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <link href="#" rel="stylesheet" type="text/css" />
    </head>
    <body>
        <form id="webform" runat="server">
            <div>
                <p><asp:Label ID="lblItem" runat="server"></asp:Label></p>
                <p><asp:Label ID="lblQuantity" runat="server"></asp:Label></p>
                <p><asp:Label ID="lblFullName" runat="server"></asp:Label></p>
                <p><asp:Label ID="lblAddressLine" runat="server"></asp:Label></p>
                <p><asp:Label ID="lblPhoneNumber" runat="server"></asp:Label></p>
                <p><asp:Label ID="lblCardNumber" runat="server"></asp:Label></p>
                <p><asp:Label ID="lblNameOnCard" runat="server"></asp:Label></p>
                <p><asp:Label ID="lblExpirationDate" runat="server"></asp:Label></p>
            </div>
        </form>
        <div id="footer">Copyright &copy; 2012 PC Land - All Rights Reserved</div>
    </body>
</html>

我得到的错误是:

Server Error in '/' Application.
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 37:         strFullName = tbxFullName.Text
Line 38:         strAddressLine = tbxAddressLine.Text
Line 39:         intPhoneNumber = tbxPhoneNumber.Text
Line 40:         intCardNumber = tbxCardNumber.Text
Line 41:         strNameOnCard = tbxNameOnCard.Text


Source File: D:\SOC Students Web Site\students\insc\insc209\project\confirm.aspx    Line: 39

Stack Trace:

[FormatException: Input string was not in a correct format.]
   Microsoft.VisualBasic.CompilerServices.Conversions.ParseDouble(String Value, NumberFormatInfo NumberFormat) +201
   Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(String Value) +66

[InvalidCastException: Conversion from string "" to type 'Integer' is not valid.]
   Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(String Value) +246
   ASP.students_insc_insc209_project_confirm_aspx.Page_Load(Object sender, EventArgs e) in D:\SOC Students Web Site\students\insc\insc209\project\confirm.aspx:39
   System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
   System.Web.UI.Control.OnLoad(EventArgs e) +99
   System.Web.UI.Control.LoadRecursive() +50
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627

它将信息放在数据库中,但显然我想摆脱错误。

1 个答案:

答案 0 :(得分:1)

通常当您看到此错误消息时:

  

输入字符串的格式不正确

它涉及将数据从一种类型转换为另一种类型,并且转换不成功。查看代码,您已将intPhoneNumber声明为类型Integer

Dim intPhoneNumber As Integer

由于VB.Net提供自动类型强制,此行试图获取电话号码文本框内容的字符串值并将其转换为数字:

intPhoneNumber = tbxPhoneNumber.Text

最有可能发生的是您的电话号码以(123) 456-7890等格式输入,无法转换为整数。如果您真的希望用户输入有效的数字,您希望提供验证和错误检查作为防御性编码实践:

If IsNumeric(tbxPhoneNumber.Text) Then
    intPhoneNumber = CInt(tbxPhoneNumber.Text)
Else
    MessageBox("Error: Please enter phone as 9-digit number.")
End If

修改:我发现您已将RequiredFieldValidator应用于电话号码。这很好,但它只会验证它已输入。如果您还希望验证它是一个9位数字,您可以使用RegularExpressionValidator。我建议将两个验证器都带有适当的错误消息,以确定它们实际验证的类型,例如:

<asp:RequiredFieldValidator ID="rfvPhoneNumber" runat="server"
    ControlToValidate="tbxPhoneNumber" 
    Display="Dynamic">
    You must enter your phone number (9 digits, no spaces or dashes)
</asp:RequiredFieldValidator>

<asp:RegularExpressionValidator" ID="revPhoneNumber" runat="server"
    ControlToValidate="tbxPhoneNumber"
    Display="Dynamic" ValidationExpression="\d{9}">
    Please enter 9-digit phone number without spaces or dashes
</asp:RegularExpressionValidator>