2016-06-21 62 views
0

这里参数值从String到的Int32转换的代码:未能在尝试将值添加到SQL数据库

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-PC\SQLSERVEREXPRESS;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 

我点击btnOK后进入一个新的数据库项目,出现异常它说:无法将参数值从字符串转换为Int32。

我做了一些调试,发现发生后的“cmd.Parameters(” @条形码“)的错误。值= txtBarcode.Text”的代码行

回答

1
cmd.Parameters.Add("@Barcode", SqlDbType.BigInt) 
cmd.Parameters("@Barcode").Value = txtBarcode.Text 

您正试图施放txtBarcode .Text作为大整数。这应该通过显式转换值来完成。您的测试用例很可能是空字符串或其他无法转换的字符串值。

请注意重新读取您的代码,这可能也是Id和Price参数的问题。