mercredi 22 juin 2016

Failed to convert parameter value from a String to a Int32 while trying to add a value to an SQL database

Here's the code:

Private m_cn As New SqlConnection
Private m_DA As SqlDataAdapter
Private m_CB As SqlCommandBuilder
Private m_DataTable As New DataTable
Private m_intRowPosition As Integer = 0


Private Sub InsertDatabaseItem_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    m_cn.ConnectionString = "Data Source=TREVOR-PCSQLSERVEREXPRESS;Initial Catalog=Milk Convience Products;Integrated Security=True"

    m_cn.Open()
    m_DA = New SqlDataAdapter("Select * From ProductIndex", m_cn)
    m_CB = New SqlCommandBuilder(m_DA)

    txtBarcode.Focus()

End Sub

Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
    Dim cmd As New SqlCommand(("INSERT INTO ProductIndex VALUES(" &
                                "@ID," &
                                "@Name," &
                                "@Price," &
                                "@Desc)" &
                                "@Barcode)"), m_cn)

    cmd.Parameters.Add("@ID", SqlDbType.Int)
    cmd.Parameters("@ID").Value = txtID.Text
    cmd.Parameters.Add("@Name", SqlDbType.VarChar)
    cmd.Parameters("@Name").Value = txtName.Text
    cmd.Parameters.Add("@Price", SqlDbType.Money)
    cmd.Parameters("@Price").Value = txtPrice.Text
    cmd.Parameters.Add("@Desc", SqlDbType.VarChar)
    cmd.Parameters("@Desc").Value = txtDesc.Text
    cmd.Parameters.Add("@Barcode", SqlDbType.BigInt)
    cmd.Parameters("@Barcode").Value = txtBarcode.Text

    cmd.ExecuteNonQuery()

    MsgBox("Success!", MsgBoxStyle.Information, "SUCCESS")

    Me.Hide()

    txtID.Clear()
    txtName.Clear()
    txtPrice.Clear()
    txtDesc.Clear()
    txtBarcode.Clear()

    m_cn.Close()
    m_cn.Dispose()
End Sub


Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
    Me.Hide()
End Sub

After I click the btnOK to enter a new database item, an exception occurs and it says : Failed to convert parameter value from a String to a Int32.

I did some debugging and found that the error occurs after the "cmd.Parameters("@Barcode").Value = txtBarcode.Text" line of code

Aucun commentaire:

Enregistrer un commentaire