简体   繁体   中英

How do i fix a “FormatException: Input string was not in a correct format”

I am doing some coding for my school project and I'm trying to create a program that uses filters and displays a set of items based on those queries. However, when writing the SQL statement, i get a FormatException.

Here is my line of code:

Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM partList WHERE [price] = '" & filterMinPrice And filterMaxPrice & "'AND [size] = '" & filterMicroATX And filterATX & "'AND [usability] = '" & filterHomeUse And filterSemiIntensive And filterHighIntensive)

and this is the error i receive:

System.InvalidCastException: 'Conversion from string "SELECT * FROM partList WHERE [pr" to type 'Long' is not valid.' FormatException: Input string was not in a correct format.

Where am I going wrong here?

I have demonstrated how to use parameters. Your main problem was in your logic in the query string. Each section of the Where clause separated by an And or Or must evaluate to True or False. Think about it. The price couldn't equal both the Max and Min. You will have to check the database to see the correct datatypes of the fields because I had to guess. The Using...End Using block ensures that the connection is closed and disposed and the command is disposed.

Private ConStr As String = "Your connection string"
Private Function GetPartData(filterMinPrice As Decimal, filterMaxPrice As Decimal, filterMicroATX As Integer, filterATX As Integer, filterHomeUse As String, filterSemiIntensive As String, filterHighIntensive As String) As DataTable
    Dim dt As New DataTable
    Dim sql = "SELECT * FROM partList 
                WHERE [price] > @MinPrice 
                And [price] < @MaxPrice 
                AND [size] > @MicroATX 
                And [size] < @ATX 
                AND [usability] = @HomeUse 
                Or [usability] = @SemiIntensive 
                Or [usability] = @HighIntensive;"
    Using con As New OleDbConnection(ConStr),
            cmd As New OleDbCommand(sql, con)
        With cmd.Parameters
            .Add("@MinPrice", OleDbType.Decimal).Value = filterMinPrice
            .Add("@MaxPrice", OleDbType.Decimal).Value = filterMaxPrice
            .Add("@MicroATX", OleDbType.Integer).Value = filterMicroATX
            .Add("@ATX", OleDbType.Integer).Value = filterATX
            .Add("@HomeUse", OleDbType.VarChar).Value = filterHomeUse
            .Add("@SemiIntensive", OleDbType.VarChar).Value = filterSemiIntensive
            .Add("@HighIntensive", OleDbType.VarChar).Value = filterHighIntensive
        End With
        con.Open()
        dt.Load(cmd.ExecuteReader)
    End Using
    Return dt
End Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM